S4muele
S4muele

Reputation: 33

How to correctly render html entities assigned to variables in React?

In React, the code below correctly renders a double quotation mark (") to the page:

export default Character() {
  return (
    <p>&quot;</p> // renders as the symbol "
  )
}

However, if the HTML entity is assigned to a variable, that entity is displayed as a string:

export default Character() {

  const char = "&quot;"

  return (
    <p>{char}</p> // renders as a the string "&quot;"
  )
}

Could anyone please explain to me why the two implementations cause different behaviors?

Thank you very much!

Upvotes: 3

Views: 4583

Answers (2)

webDev_
webDev_

Reputation: 148

You can use <>fragment</>

export default Character() {

  const char = <>&quot;</>

  return (
    <p>{char}</p>
  )
}

Upvotes: 2

Amila Senadheera
Amila Senadheera

Reputation: 13235

Following is considered as HTML content and processed by HTML before rendering.

<p>&quot;</p>

When you set it using a string reference(in React) preprocessing of symbols in the string is ignored somehow.

<p>{char}</p>

If you have a string with HTML Symbols, you can use dangerouslySetInnerHTML attribute in React to get rid of the issue.

<p dangerouslySetInnerHTML={{ __html: char }} />

To avoid XSS, sanitize the string using sanitize-html.

  1. Install the package
npm i sanitize-html
  1. Simply use it like below
import sanitizeHtml from 'sanitize-html';
...
...
<p dangerouslySetInnerHTML={{ __html: sanitizeHtml("your-text<script src=""></script>") }} />

Output will be => "your-text" by ignoring the script section.

Code Sandbox

Upvotes: 3

Related Questions