Skip to content

Instantly share code, notes, and snippets.

@markmur
Created December 5, 2017 21:20
Show Gist options
  • Save markmur/47db54293bc8bfb3c54ab1cf25a3ad5c to your computer and use it in GitHub Desktop.
Save markmur/47db54293bc8bfb3c54ab1cf25a3ad5c to your computer and use it in GitHub Desktop.
Render Components as String
const renderProp = (key, val) => {
const type = typeof val;
if (type === 'string' && !val) return null;
if (type === 'object' && !Object.keys(val).length) return null;
switch (type) {
case 'number':
return `${key}={${val}}`;
case 'string':
return `${key}="${val}"`;
case 'object':
return `${key}="${JSON.stringify(val)}"`;
case 'function':
return `${key}={Function}`;
default:
return null;
}
};
const renderProps = props =>
Object.keys(props).reduce((str, prop) => {
if (prop !== 'children') {
const attr = renderProp(prop, props[prop]);
if (attr) str += ` ${attr}`;
}
return str;
}, '');
const renderChildren = children =>
children.map(
child =>
`<${child.type.displayName || child.type.name}${renderProps(
child.props
)}${child.props.children && child.props.children.length ? '' : ' /'}>
${
typeof child.props.children === 'string'
? child.props.children
: child.props.children &&
child.props.children.length &&
child.props.children.map
? renderChildren(child.props.children)
: ''
}
${
child.props.children
? `</${child.type.displayName || child.type.name}>`
: ''
}
`
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment