简体   繁体   中英

How to pass react component into dangerouslySetInnerHtml?

Suppose I cannot change this statement in my sourcecode:

<div dangerouslySetInnerHTML={{ __html: template }} />  

How can I replace the template for a react component? Like:

<div dangerouslySetInnerHTML={{ __html: someReactComponent }} />  

How can in insert a reactjs component in ?

As commented by FrankerZ ,

Why do you even have to do this? <div><someReactComponent /></div> . There's a reason why it uses the word "dangerously"...avoid using it if you have to.

Yes, obviously. You shouldn't be using dangerouslySetInnerHTML most of the time as far as possible.

If you are trying to render static markup, then you may use renderToStaticMarkup . The linked post has also stated that but will not work because it is being used from React instance. You need to use it from ReactDOMServer :

import ReactDOMServer from 'react-dom/server';
ReactDOMServer.renderToStaticMarkup(statticElement)

This doesn't create extra DOM attributes that React uses internally, such as data-reactroot. This is useful if you want to use React as a simple static page generator, as stripping away the extra attributes can save some bytes.

See the docs for more information on it.

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