Is there some way to avoid HTML escaping of text children when calling React.createElement?

aknuds1 picture aknuds1 · Dec 11, 2015 · Viewed 10.5k times · Source

Consider the following call to React.createElement:

React.createElement('span', null, null, ['><',])

This will cause React to escape > and <. Is there some way to avoid this text being escaped?

Answer

Oleksandr T. picture Oleksandr T. · Dec 11, 2015

You can use dangerouslySetInnerHTML

const Component = () => (
   <span dangerouslySetInnerHTML={{ __html: '&gt;&lt;' }} />
);
 
ReactDOM.render(
   <Component />, document.getElementById('container')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="container"></div>

or use Unicode codes instead of HTML special characters

const Component = () => (
  <span>{'\u003E\u003C'}</span>
);

ReactDOM.render(
  <Component />, document.getElementById('container')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="container"></div>