Reputation: 210
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
™
rather than
My Title™
Why is this happening?
Upvotes: 0
Views: 2394
Reputation: 15325
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>™</span>]
Second, you can use dangerouslySetInnerHtml
even though it's not recommended because, well, it's dangerous.
return <div dangerouslySetInnerHTML={{__html: title}}></div>
For completeness, @Tom Fenech showed two other elegant solutions in his answer.
Full working code:
var Example = React.createClass({
render: function() {
var listTitle = ["My Title", <span>™</span>]
var dangerousTitle = "My other Title™";
return <div>
{listTitle}<br/>
<div dangerouslySetInnerHTML={{__html: dangerousTitle}}></div>
</div>;
}
});
ReactDOM.render(
<Example/>,
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>
Upvotes: 1
Reputation: 74595
If you want to include a ™ symbol in a string, then either use the character itself directly, or refer to it using \u2122
(the unicode code point).
As long as your files are saved and served up in the correct encoding, then you shouldn't have a problem with either approach.
function testComponent() {
return React.DOM.div(null,
React.DOM.h3(null, "My Title™"),
React.DOM.h3(null, "My Title\u2122"));
}
ReactDOM.render(React.createElement(testComponent),
document.getElementById("root"));
<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="root"></div>
Upvotes: 1