react-html-parser
react-html-parser copied to clipboard
Grab the innerHTML
Hey there,
thanks for this great package. Is it possible to grab the inner html of an element as a string in the transform function?
Here's an example
const html = '<div data-will-be-transformed><h1>Hello</h1>....! <b>WORLD</b></div>
const transform = (node, index) => {
// custom helper function
if(!isEmptyObject(node.attribs)) {
switch(true) {
case 'data-will-be-transformed' in node.attribs:
// would want to grab the inner html of my div as a string
const innerHtml = processNodes(node.children, transform);
// this resulted in no good
// processNodes(node.children, transform).map(node => convertNodeToElement(node));
return(
<MyCustomComponet
myProp={innerHtml}
/>
);
default:
return
}
}
};
ReactHtmlParser(html, { transform: transform })
Thanks in advance.
UPDATE:
When looking into htmlparser2
I found getInnerHTML
. This seems to work.. is there a better way?
const innerHTML = htmlparser2.DomUtils.getInnerHTML(node);
Thanks for posting the update bit, that works. It apparently may break if there are double quotes in attributes: https://github.com/fb55/domutils/issues/29 and is to be considered deprecated.
Documentation for DomUtils or dom-serializer is non-existent so I'm sticking with this for my simple use case, but apparently it's better to use dom-serializer.
Adding a follow up here for people who are looking at this in the future.
Documentation on dom-serializer is light because it just does one job and it does it well. You should already have the dom-serializer package installed if you have htmlparser2 installed.
If you want to see my change from htmlparser2.DomUtils.getInnerHTML to dom-serializer the commit it linked. The interesting thing is that dom-serializer acts more like getOuterHTML so you have to specify childNodes to get it to work the same.
I write my JS more Object Oriented but you can apply the same pattern any way you like.