How to convert HTML string to virtual DOM in React?

I would like to be able to take the raw HTML string that I insert into the React component through dangerouslySetInnerHTMLand include it in the virtual DOM. Is there any way to do this?

For example, if I have:

<Component dangerouslySetInnerHTML={{__html: htmlFromServer}}></Component>

How can I get htmlFromServerinto the virtual DOM? Thanks!

+4
source share
2 answers

Parts of Facebook React Magic do what you want:

https://github.com/reactjs/react-magic

+2
source

You can do it initially DOMParser.

eg:.

let doc = new DocParser().parseFromString(htmlFromServer, 'text/html'),
    body = doc.querySelector('body'),
    div = document.createElement('div');

div.textContent = 'You DOM manipulator, you.';
body.appendChild(div);

return <Component dangerouslySetInnerHTML={{__html: body.innerHTML}}></Component>;
+1
source

Source: https://habr.com/ru/post/1607920/


All Articles