I have a string in unicode that i need to convert. I need to render the string with \\u00f3 to ó. This is an example, it should happen with all other types of characters, á
Just pass it as a JS string:
<Hello name={'Informaci\u00f3n'} />
No need to do any manual processing (which is error prone).
Fiddle: https://jsfiddle.net/ffffdf7o70/5/
React converts unicode automatically with the dangerouslySetInnerHTML attribute.
See for more info: https://reactjs.org/docs/dom-elements.html
export default class Hello extends Component {
render() {
return (
<div>
<div dangerouslySetInnerHTML={{ __html: this.props.name}}></div>
</div>
);
}
}
If you have to work with strings that have, for whatever reason, those \u....
codes in them instead of being real letters, convert them to numbers, and then use String.fromCharCode() to turn those numbers into real letters. We can use a regexp replace with handler function for this:
function convertUnicode(input) {
return input.replace(/\\u(\w\w\w\w)/g,function(a,b) {
var charcode = parseInt(b,16);
return String.fromCharCode(charcode);
});
}
var Hello = React.createClass({
getInitialState: function() {
return {
name: convertUnicode(this.props.name)
};
},
render: function() {
return <div>Hello {this.state.name}</div>;
}
});
React.render(
<Hello name="Informaci\u00f3n" />,
document.getElementById('container')
);
Fiddle: https://jsfiddle.net/ffffdf7o70/4/
Question title leads to this questions around React unicode issues, and sometimes simply this meta
tag is needed:
<html>
<head>
<meta charset="UTF-8">
</head>
</html>
To put the unicode write in your render()
and jsx, you can just:
<div>{'First \u00b7 Second'}</div>
, or
<div>{'First ' + String.fromCharCode(183) + ' Second'}</div>
If doing this with libraries and other fonts, be sure that your font is imported first, make sure that you are using font-family: myFont
(i.e. "Font Awesome 5 Free"
). And make sure that the unicode that you are using is accurate.