Stanley Luo Stanley Luo - 5 months ago 66
React JSX Question

HTML in React and ES6 Template Literal

I'm passing some text to a 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?


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


dangerouslySetInnerHTML is 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 out dangerouslySetInnerHTML and pass an object with a __html key, to remind yourself that it's dangerous. For example:

function createMarkup() {
  return {__html: 'First &middot; Second'};

function MyComponent() {
  return <div dangerouslySetInnerHTML={createMarkup()} />;