2

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?

Ferran Buireu
  • 28,630
  • 6
  • 39
  • 67
Lone Wallaby
  • 159
  • 1
  • 1
  • 9

1 Answers1

3

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).

idmean
  • 14,540
  • 9
  • 54
  • 83
  • That works perfectly, thanks a lot. How would that work with more complex emojis, say flags, that use two CharCodes together? – Lone Wallaby Jul 30 '21 at 14:30
  • fromCodePoint (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fromCodePoint) accepts multiple code points. You could store an array in your object for each emoji and then spread it into fromCodePoint (`fromCodePoint(...milkoji[milk]`). Please note that char codes are something very different from code points. – idmean Jul 30 '21 at 14:38