11

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?

aknuds1
  • 65,625
  • 67
  • 195
  • 317

1 Answers1

21

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>
Oleksandr T.
  • 76,493
  • 17
  • 173
  • 144
  • Works fine when need print a html header using `
    ` and colored code, reactjs strip newlines.
    – e-info128 Aug 11 '21 at 00:13
  • 1
    This is a horribly insecure example. If you use dangerouslySetInnerHTML then please DOMPurify.sanitize this content! – Manicode Apr 20 '22 at 18:15