Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 214
aknuds1 Avatar asked Dec 11 '15 20:12

aknuds1


1 Answers

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>
like image 64
Oleksandr T. Avatar answered Oct 10 '22 21:10

Oleksandr T.