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

View File

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