Seth G Seth G - 1 month ago 17
React JSX Question

HTML Element with React variable does not display ASCII

I have a custom title being received and set in a JS variable. But the output shows the ASCII code instead of the symbol. Here is a simple example of the render function:

render() {
var title = "My Title™"
return <div>{title}</div>;
}


And the output is


My Title
&#8482;



rather than


My Title™


Why is this happening?

Answer

You are trying to insert html from a string, even if it's not a tag.

So you have two easy solutions to fix this.

First you can wrap this element in a tag and insert it afterwards:

var title = ["My Title", <span>&#8482</span>]

Second, you can use dangerouslySetInnerHtml even though it's not recommended because, well, it's dangerous.

return <div dangerouslySetInnerHTML={{__html: title}}></div>

Full working code:

var WithAList = React.createClass({
  render: function() {
     var title = ["My Title", <span>&#8482;</span>]
     return <div>{title}</div>;
  }
});

ReactDOM.render(
  <WithAList/>,
  document.getElementById('container1')
);

var Dangerous = React.createClass({
  render: function() {
     var title = "My other Title&#8482;"
     return <div dangerouslySetInnerHTML={{__html: title}}></div>;
  }
});

ReactDOM.render(
  <Dangerous/>,
  document.getElementById('container2')
);
<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="container1">
</div>
<div id="container2">
</div>