Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Render HTML Symbols

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?

like image 566
johannchopin Avatar asked Nov 19 '25 20:11

johannchopin


1 Answers

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.

like image 142
Quentin Avatar answered Nov 22 '25 08:11

Quentin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!