I'm passing some text to a component:
<Component
text={`text with <span style={{fontWeight:bold}}>${thisPart}</span> emphasized`}
/>
Although it certainly can't work but I guess it shows my intentions well. Any idea how to make it work?
Do not use dangerouslySetInnerHTML for this. That is an anti-pattern.
<MyComponent>
<span>text with</span>
<strong>{thisPart}</strong>
<span>emphasized</span>
</MyComponent>
The 2 span and 1 strong elements are accessible via the MyComponent children property
class MyComponent extends React.Component {
render () {
return (
<div>
<p>some text</p>
<p>{this.props.children}</p>
</div>
)
}
}
Would render
<div>
<p>some text</p>
<p>
<span>text with</span>
<strong>this part</strong>
<span>emphasized</span>
</p>
</div>
You cannot pass stringified HTML to a component because it opens XSS vulnerabilities.
If you must render html then you are required to use dangerouslySetInnerHTML
dangerouslySetInnerHTMLis React's replacement for using innerHTML in the browser DOM. In general, setting HTML from code is risky because it's easy to inadvertently expose your users to a cross-site scripting (XSS) attack. So, you can set HTML directly from React, but you have to type outdangerouslySetInnerHTMLand pass an object with a __html key, to remind yourself that it's dangerous. For example:
function createMarkup() {
return {__html: 'First · Second'};
}
function MyComponent() {
return <div dangerouslySetInnerHTML={createMarkup()} />;
}