Reputation: 14844
I created a Symbol
component in React to easily render HTML Symbols by name like euro
will render €
(€) or sum
render ∑
(∑).
Issue is that if I just render the HTML code I will see the code on the screen and not the symbol. So I had to use the dangerouslySetInnerHTML prop on a span
element to render it as HTML:
const SYMBOLS = {
euro: '€',
sum: '∑'
}
const Symbol = (props) => {
const { entity } = props
return <span dangerouslySetInnerHTML={{ __html: SYMBOLS[entity] }} />
}
export default Symbol
This is working fine but it doesn't feel right to wrap the symbols in an 'unnecessary' span
. So has someone an idea how I could render an HTML symbol in React without using extra wrappers?
Upvotes: 3
Views: 1502
Reputation: 524
You can show symbol in JSX but in your code that is not correctly parsed.
You should use ReactHtmlParser
package to parse your SYMBOL[entity] on JSX
Try to install this package.
npm install "react-html-parser" --save
This is complete code of your Symbol component
import React from 'react';
import ReactHtmlParser from "react-html-parser";
const SYMBOLS = {
euro: '€',
sum: '∑'
}
const Symbol = (props) => {
const { entity } = props;
return (
{ReactHtmlParser(SYMBOLS[entity])}
);
}
export default Symbol;
And use Symbol code
<Symbol entity="euro" />
Upvotes: 0
Reputation: 943579
dangerouslySetInnerHTML
is the standard way to deal with raw HTML in React.
It should be avoided, but the way to do that is to avoid using raw HTML.
Type a €
or use the JavaScript escape sequence: "\u20AC"
const SYMBOLS = {
euro: "\u20AC",
sum: '∑'
}
Sites like File Format Info are a good source to identify the correct escape sequence or to get a character you can copy/paste.
Upvotes: 3