react-html-parser icon indicating copy to clipboard operation
react-html-parser copied to clipboard

Grab the innerHTML

Open entiendoNull opened this issue 5 years ago • 2 comments

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);

entiendoNull avatar Feb 25 '19 12:02 entiendoNull

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.

aguilarm avatar Oct 29 '19 19:10 aguilarm

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.

jimlind avatar Oct 31 '21 15:10 jimlind