Reputation: 41
I'd like to be able to take a raw HTML string that I insert into a React component via dangerouslySetInnerHTML
and have it incorporated into the virtual DOM. Is there any way to do this?
For example, if I have:
<Component dangerouslySetInnerHTML={{__html: htmlFromServer}}></Component>
how can I get htmlFromServer
into the virtual DOM? Thanks!
Upvotes: 4
Views: 4211
Reputation: 26253
You can do this natively with DOMParser
.
E.g.:
let doc = new DOMParser().parseFromString(htmlFromServer, 'text/html'),
body = doc.querySelector('body'),
div = document.createElement('div');
div.textContent = 'DOM manipulated.';
body.appendChild(div);
return <Component dangerouslySetInnerHTML={{__html: body.innerHTML}}></Component>;
Upvotes: 2
Reputation: 7606
Parts of Facebook's React Magic does what you want:
https://github.com/reactjs/react-magic
Upvotes: 2