Created
December 5, 2017 21:20
-
-
Save markmur/47db54293bc8bfb3c54ab1cf25a3ad5c to your computer and use it in GitHub Desktop.
Render Components as String
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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