In React, the code below correctly renders a double quotation mark (") to the page:
export default Character() {
return (
<p>"</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 = """
return (
<p>{char}</p> // renders as a the string """
)
}
Could anyone please explain to me why the two implementations cause different behaviors?
Thank you very much!
Following is considered as HTML content and processed by HTML before rendering.
<p>"</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.
npm i sanitize-html
import sanitizeHtml from 'sanitize-html';
...
...
<p dangerouslySetInnerHTML={{ __html: sanitizeHtml("your-text<script src=""></script>") }} />
Output will be => "your-text" by ignoring the script
section.