How to add Unicode in React.js?

When dealing with Unicode characters in props, it’s important to be able to render them correctly inside our components. When rendered, the Unicode should be evaluated and its representation should appear in the UI.

So, how can you add Unicode in React.js?

Unicode can be added to React.js by passing the Unicode characters into JSX brackets. When rendered, the Unicode values will be outputted correctly.

For example, let’s say we have the name prop:

Éire

But there is a difference, this string has a fada, and is sent to us in Unicode:

%C9ire
// Éire

In order for the text to be outputted correctly, we can use JSX { } brackets:

const TranslatedName = React.createClass({
  render: function() {
    return <div>Name: {this.props.name}</div>;
  }
});

ReactDOM.render(
  <TranslatedName name={'%C9ire'} />,
  document.getElementById('app')
);

Let’s break this down:

  • We pass %C9ire inside the name prop.
    • It gets rendered inside our <TranslatedName /> component.
  •  Inside our render function, {this.props.name}successfully renders our string and its Unicode characters.

Using dangerouslySetInnerHtml

Additionally, React.js converts Unicode automatically with the dangerouslySetInnerHTML attribute:

export default class TranslatedName extends Component {
  render() {
    return (
      <div>
        <div dangerouslySetInnerHTML={{ __html: this.props.name }}></div>
      </div>
    );
  }
}

However, be wary that there are security concerns using  dangerouslySetInnerHTML.

And there you have it, Unicode evaluation is more or less taken care of by JSX brackets. 

Proudly published with Gatsby