-
-
Save Convicted202/f132e0874c2f3ae89d41b797fc782485 to your computer and use it in GitHub Desktop.
XML to React Component
This file contains 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 xml = ` | |
<XMLText class="yeah-attributes"> | |
regular text | |
<XMLBold> | |
bold text | |
</XMLBold> | |
another text | |
</XMLText> | |
`; | |
// Some simple components | |
class Text extends React.Component { | |
render () { | |
return ( | |
<div className={this.props.class}>{this.props.children}</div> | |
); | |
} | |
} | |
class Bold extends React.Component { | |
render () { | |
return ( | |
<b>{this.props.children}</b> | |
); | |
} | |
} | |
const XMLNodeToReactComponentMap = { | |
'XMLText': Text, | |
'XMLBold': Bold | |
}; | |
const parser = new DOMParser(); | |
const xmlDoc = parser.parseFromString(xml, 'text/xml'); | |
function processChildren (children) { | |
return Array.from(children.length ? children : []).map( | |
(node, i) => { | |
// return if text node | |
if (node.nodeType === 3) return node.nodeValue; | |
// collect all attributes | |
let attributes = Array.from(node.attributes).reduce((attrs, attr) => { | |
attrs[attr.name] = attr.value; | |
return attrs; | |
}, {}); | |
// create React component | |
return React.createElement(XMLNodeToReactComponentMap[node.nodeName], { | |
...attributes, | |
key: i | |
}, processChildren(node.childNodes)); | |
}); | |
} | |
// root component | |
class XMLtoReact extends React.Component { | |
render () { | |
return ( | |
<div> | |
{processChildren(Array.from(xmlDoc.childNodes))} | |
</div> | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
test