1

What I want is a really simple React component that returns a random emoji out of a list of allowed ones, for readability I've just created a string with all the allowed emoji I want it to choose from and then returning a random one, but what I'm getting is the �-symbol (unicode replacement char).

This is my code:

import React from 'react';

export default () => {
  const allowedEmoji = '✌️';
  return (
    <span role="img" aria-label="hello">
      {allowedEmoji[Math.floor(Math.random() * allowedEmoji.length)]}
    </span>
  );
};

I'm guessing this has to do with encoding and emojis in a string taking up more than one index? Can someone please clarify this?

Didrik Grip
  • 11
  • 1
  • 3
  • 1
    I guess it has to do with bite each character takes. An emogi takes 32 bits and 1 string character takes 16. – Rajesh Feb 12 '20 at 10:39
  • 2
    an array might be a better solution in this case – Natrium Feb 12 '20 at 10:39
  • 1
    `[...allowedEmoji][Math.floor(Math.random() * allowedEmoji.length)]` will do the trick. – AZ_ Feb 12 '20 at 10:41
  • do `const allowedEmoji = [...'✌️'];` and best is you'd do it outside of the function. – Thomas Feb 12 '20 at 10:41
  • 2
    @AZ_ no it won't because `allowedEmoji.length` is wrong. Compare `allowedEmoji.length` and `[...allowedEmoji].length` – Thomas Feb 12 '20 at 10:43
  • @Thomas yeah need to create the array first then use the variable. – AZ_ Feb 12 '20 at 10:44
  • Adding to my first comment, you can try something like this to achieve value: https://jsfiddle.net/RajeshDixit/3d5L8jsu/ – Rajesh Feb 12 '20 at 10:45

0 Answers0