Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ascii/HTML character code doesn't work within React variable

I have the ascii/html code of a checkmark: ✔

✔

In react if I go:

<div>&#10004;</div>

then it works. but if I go

var str = '&#10004;';
<div>{str}</div>

it doesn't. It shows up as &#10004;

any ideas?

class Hello extends React.Component {
  render() {
    var checkmark = '&#10004;';
  
    return <div>Hello {checkmark}</div>;
  }
}

ReactDOM.render(
  <Hello />,
  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"/>
like image 415
Shai UI Avatar asked Jan 04 '18 21:01

Shai UI


1 Answers

It's pretty easy to see what's going on here by looking at what actually gets rendered:

const checkmark = '&#100004;';

ReactDOM.render(<div id="x">{checkmark}</div>,
  document.getElementById('container'));

console.log(document.getElementById('x').innerHTML);
<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"/>

As you can see, React escapes its output, replacing & with &amp;, just as expected.

The easiest, and correct, solution is to dump the HTML entity and just use the character directly:

class Hello extends React.Component {
  render() {
    var checkmark = '✔';
    return <div>Hello {checkmark}</div>;
  }
}

ReactDOM.render(<Hello />, 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"/>

As long as your page's encoding is declared correctly as UTF-8, this will work in all browsers.

like image 130
Jordan Running Avatar answered Oct 09 '22 01:10

Jordan Running