ealush / emoji-picker-react

The most popular React Emoji Picker
https://ealush.com/emoji-picker-react/
MIT License
1.04k stars 171 forks source link

Feature request: Emoji text renderer #290

Open Sodj opened 1 year ago

Sodj commented 1 year ago

It would be very helpful to have a function that takes text containing emojis and returns react object that converts the character emojis to component emojis using <Emoji .../>

ealush commented 1 year ago

Should be pretty straightforward to implement really. I'm overloaded with other work (both OSS and work), but I'd love to see a PR. The basis for this would be to split the string, identify the emojis, then map into components.

Obviously, this would work with simple strings, but what if you want to have markup within that string? Need to think how to handle that as well.

Sodj commented 1 year ago

I know it should be straight forward but I did try to do just that but failed. Then thought it would be neat if it came with the package

ealush commented 1 year ago

I'd love to help with guidance on this.

Could you give a sample string that you've tried to convert and try to explain what you attempted?

Sodj commented 1 year ago

Well I deleted my attempt but it was like this:

var msg = "Hello 👋 world"
var output = msg.split(emojiRegex) 
// gives : [hello, 👋, world]

return 
<div>
{output.map(e=>{
  if(isEmoji(e)) return <Emoji unified={emojiToUnicode(e)} />
  else return e
})}
</div>

But I was getting the same error I got when I passed wrong unicode

My issue was most likely in either the emojiRegex or the emojiToUnicode, if you could suggest some reliable regex and converter that would be superb

Sodj commented 1 year ago

@ealush Update: Upon further testing I found that the issue is in my emojiToUnicode function which sometimes returns NaN for special emojis like ♥,🇦🇫 and ♥️ (different heart)

It would be nice if the Emoji component could take either unified or emoji as param like <Emoji emoji="🇦🇫" /> Or have an exported function from the module emojiToUnicode

Also it would be nice if the component would just render nothing instead of throwing an error when the unified code isn't correct

ricklove commented 1 year ago

Here is a workaround - might submit a PR to implement this:

// based on https://stackoverflow.com/a/58691389/567524
const emojiToUnified = (emoji: string) => {
    const code = [...emoji]
        .map((x) => x.codePointAt(0) ?? 0)
        .filter(n => n > 0xfff || n === 0x200d || (0xfe00 <= n && n <= 0xfeff))
        .map(x => x.toString(16))
        .join(`-`);
    console.log(`emojiToUnicode`, { emoji, code });
    return code;
};

// usage:
<Emoji unified={emojiToUnified(value)} />