Displaying emojis programmatically in JSX (Gatbsy)

Viewed 109

I have the following JSX code:

import * as React from 'react'

const CheeseIcons = ({ milk }) => {
  const milkoji = {
    Cow:'1F42E',
    Goat: '1F410'
  }

  const icon = "&#x" + milkoji.[milk] + ";";
  return (
    <main>
      <p>{icon}</p>
      <p>&#x1F42E;</p>
    </main>
  )
}

export default CheeseIcons

I am passing Cow correctly as {milk} - but in the first paragraph the text &#x1F42E; is displayed, whereas in the second paragraph the emoji is displayed.

How do I get the emoji to be displayed in the first paragraph?

1 Answers

After reconsideration, this question is not a clear duplicate because it deals specifically with emojis which can only be encoded in UTF-16 with surrogate pairs, which make the answers from the linked question unsuitable.

You would therefore do:

const CheeseIcons = ({ milk }) => {
  const milkoji = {
    Cow: 0x1F42E, // Attention
    Goat: 0x1F410
  }

  return (
    <main>
      <p>{String.fromCodePoint(milkoji[milk])}</p>
    </main>
  )
}

Note that we use String.fromCodePoint instead of String.fromCharCode as the values above are code points (but not valid UTF-16 bytes encoding these emojis).

Related