简体   繁体   中英

How to convert an HTML string to virtual DOM in React?

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!

Parts of Facebook's React Magic does what you want:

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

You can do this natively with 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>;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM