2

I'm using custom fonts in my site, similar to Font Awesome, which have simple signature:

<i className="icon-plus"></i>

But I want to create own component which will be render dynamic HTML entities like:

const iconEntity = '&#xf2b9;' // (Font Awesome HTML entity example)
const icon1 = '&#xf13d;' // dynamic entities

class OwnIcon extends React.Component {
  render() {
   return <i>{iconEntity}</i>
  }
}

But this doesn't work. After reading this post I trier using dangerouslySetInnerHTML and it works, e.g.:

const iconEntity = '&#xf2b9;'

class OwnIcon extends React.Component {
  render() {
    return <i className="icon" dangerouslySetInnerHTML={{__html: iconEntity }}></i>
  }
}

But it's a little bit ugly solution. After reading JSX gotchas I found that there are solutions like:

A safer alternative is to find the unicode number corresponding to the entity and use it inside of a JavaScript string:

<div>{'First \u00b7 Second'}</div>
<div>{'First ' + String.fromCharCode(183) + ' Second'}</div>

But how I could convert(for example, Font Awesome) Unicode Private-Use characters "\f007" or HTML hex entity&#xf007 to get unicode number to get rid of dangerouslySetInnerHTML and render icons in more "clear" way?

Text examples: here

dieTrying
  • 367
  • 1
  • 6
  • 14
  • Why not use the same system as FA? Create classes for each entity with a `::before { content: >entity< }` and apply that class to your `` tag? – ChrisR Jun 20 '18 at 11:26
  • For some reason requirements forced me for this solution without using pseudo elements, so I'm looking for the best way to render it as HTML hex entity. – dieTrying Jun 20 '18 at 11:47

1 Answers1

1

Put it in a Fragment so the value becomes JSX, and will be output as HTML:

const iconEntity = <Fragment>&#xf2b9;</Fragment>

class OwnIcon extends React.Component {
  render() {
    return <i className="icon">{iconEntity}</i>
  }
}

The downside to this, of course, is that you don't get to say "Let's get dangerous!" like Darkwing Duck. ;)

NotoriousWebmaster
  • 3,298
  • 7
  • 37
  • 49