Skip to content

Instantly share code, notes, and snippets.

@mjschutz
Last active October 30, 2020 08:35
Show Gist options
  • Save mjschutz/e5b779f1f2405a653f3a1e3632d7369f to your computer and use it in GitHub Desktop.
Save mjschutz/e5b779f1f2405a653f3a1e3632d7369f to your computer and use it in GitHub Desktop.
Generate a XML on React from ReactElements/Nodes
import React from 'react';
import {create as createXML} from 'xmlbuilder2';
import { XMLBuilder, XMLBuilderCreateOptions, DefaultBuilderOptions, XMLWriterOptions } from "xmlbuilder2/lib/interfaces";
function renderXMLElement(root: XMLBuilder, {type, props}: React.ReactElement) {
let node = root;
if (typeof type !== 'symbol') {
const elementName = typeof type == 'function' ? type.name: type;
if (typeof type == 'function') {
let e: React.ReactElement;
if (!!(type.prototype && type.prototype.isReactComponent)) {
e = new (type as any)(props).render();
} else {
e = (type as Function)(props);
}
return renderXMLElement(root, e);
}
node = root.ele(elementName, (({children, ...props}: {children?: any, [props: string]: any}) => props)(props));
}
if ('children' in props) {
React.Children.map(props.children, child => {
if (React.isValidElement(child)) {
renderXMLElement(node, child);
} else {
node.txt(String(child));
}
})
}
if (root != node)
node.up();
return root;
}
export default {
renderToString(element: React.ReactElement, writerOptions: XMLWriterOptions = {}, builderOptions: XMLBuilderCreateOptions = DefaultBuilderOptions):string {
return renderXMLElement(createXML(builderOptions), element).end(writerOptions);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment