Home > front end >  How to display 'A & B' instead of 'A & B' in NextJs?
How to display 'A & B' instead of 'A & B' in NextJs?

Time:10-07

I am trying to display 'A & B' but NextJs is displaying it as A & B as the original string from the API. Could anyone of you please let me know how I could update '&' or other symbols to their original form instead of code?

CodePudding user response:

React escapes html entities. You can explicitly disable it via dangerouslySetInnerHTML if you want to emit raw html, but you should not do this unless you are 100% certain that the html will never contain malicious code. If it's possible that it will contain user input, for example do not do this or you're subjecting yourself to security vulnerabilities.

The snippet below uses React.createElement because I still haven't figured out how to get JSX to work in SO snippets, but it's the equivalent of:

<div>{text}</div>
<div dangerouslySetInnerHTML={{__html: text}}></div>

const text = "A &amp; B";

const unescaped = React.createElement('div', {}, text);
const escaped = React.createElement('div', { dangerouslySetInnerHTML: { __html: text} })

ReactDOM.render(unescaped, document.getElementById('a'));
ReactDOM.render(escaped, document.getElementById('b'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="a"></div>
<div id="b"></div>

  • Related