Adding a unicode escape to a dynamic string value

Viewed 381

I cant figure out how to correctly add a unicode escape to a dynamic string value in order to render emojis in React.

In my database I am storing the hexcode for that emoji (1f44d)

I've created a styled-component with the correct css to render an emoji

const EmojiWrapper = styled.span(({ label }) =>
  css({
    role: 'img',
    ariaLabel: label || '',
    ariaHidden: label ? 'false' : 'true',
  })
);

and the usage where symbol is equal to 1f44d just displays '\u{1f44d}'

<EmojiWrapper className="emoji" label={label}>
   {`'\\u{${symbol}}'`}
</EmojiWrapper>

I've tried storing the hexcode as an escaped string '\u{1f44d}' but that still displays '\u{1f44d}' as opposed to the emoji.

If I hardcode the hexcode with the escape '\u{1f44d}' the emoji renders correctly:

<EmojiWrapper className="emoji" label={label}>
   {'\u{1f44d}'}
</EmojiWrapper>

As does

{eval("'\\u" + {symbol} + "'")}

I am trying to avoid using eval however as I've read it is a bad idea. Any ideas would be much appreciated.

1 Answers

You can use String.fromCodePoint(), this method has been added to ECMAScript 2015. Here you will find the Polyfill in case of problems with the browser compatibility:

const symbol = "1f44d";

<EmojiWrapper className="emoji" label={label}>
   {String.fromCodePoint(`0x${symbol}`)} // encoding UTF-32/UTF-32BE (hex)
</EmojiWrapper>
Related