Refactoring rendering root to be a component

This commit is contained in:
Jeff Avallone 2018-02-17 11:16:05 -05:00
parent dea6d92272
commit 3ead0c13df
2 changed files with 19 additions and 16 deletions

View File

@ -6,7 +6,7 @@ import style from './style.css';
import Form from 'components/Form'; import Form from 'components/Form';
import Message from 'components/Message'; import Message from 'components/Message';
import renderImage from 'components/SVG'; import SVG from 'components/SVG';
import { syntaxes, demoImage } from 'devel'; import { syntaxes, demoImage } from 'devel';
class App extends React.PureComponent { class App extends React.PureComponent {
@ -100,7 +100,7 @@ class App extends React.PureComponent {
<p>Sample warning message</p> <p>Sample warning message</p>
</Message> </Message>
{ image && <div className={ style.render }> { image && <div className={ style.render }>
{ renderImage(image, { ref: this.imageRef }) } <SVG data={ image } imageRef={ this.imageRef }/>
</div> } </div> }
</React.Fragment>; </React.Fragment>;
} }

View File

@ -1,4 +1,5 @@
import React from 'react'; import React from 'react';
import PropTypes from 'prop-types';
import Box from './Box'; import Box from './Box';
import HorizontalLayout from './HorizontalLayout'; import HorizontalLayout from './HorizontalLayout';
@ -18,24 +19,26 @@ const nodeTypes = {
VerticalLayout VerticalLayout
}; };
const renderChildren = children => { const render = (data, extraProps = {}) => {
if (!children || children.length === 0) { if (typeof data === 'string') {
return; return data;
} }
return children.length === 1 ? const { type, props } = data;
renderImage(children[0]) : const children = (data.children || []).map(
children.map((node, i) => renderImage(node, { key: i })); (data, key) => render(data, { key }));
return React.createElement(
nodeTypes[type],
{ ...extraProps, ...props },
children.length === 1 ? children[0] : children);
}; };
const renderImage = (node, extraProps = {}) => { const SVG = ({ data, imageRef: ref }) => render(data, { ref });
if (typeof node === 'string') {
return node;
}
const { type, props, children } = node; SVG.propTypes = {
data: PropTypes.object.isRequired,
return React.createElement(nodeTypes[type], { ...extraProps, ...props }, renderChildren(children)); imageRef: PropTypes.func
}; };
export default renderImage; export default SVG;