Skip to content

Instantly share code, notes, and snippets.

@chibicode
Last active February 24, 2024 18:08
Show Gist options
  • Star 47 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save chibicode/fe195d792270910226c928b69a468206 to your computer and use it in GitHub Desktop.
Save chibicode/fe195d792270910226c928b69a468206 to your computer and use it in GitHub Desktop.
A dead simple React.js Twemoji component.

Twemoji + React

A dead simple React Twemoji component.

Requirements: twemoji

npm install --save twemoji

# or

yarn add twemoji
import React from 'react'
import Twemoji from './Twemoji'
const Example = () => (
<p>
Hello! <Twemoji emoji="👋" />
</p>
)
export default Example
.emoji {
display: inline-block;
width: auto;
height: 1em;
vertical-align: -0.125em;
}
import React, { memo } from 'react'
import twemoji from 'twemoji'
const Twemoji = ({ emoji }) => (
<span
dangerouslySetInnerHTML={{
__html: twemoji.parse(emoji, {
folder: 'svg',
ext: '.svg'
})
}}
/>
)
export default memo(Twemoji)
@lmssieh
Copy link

lmssieh commented Sep 1, 2022

@NekoChanTaiwan works great, thanks for sharing!

@dejurin
Copy link

dejurin commented May 15, 2023

UPDATE

import React from 'react';
import NextImage from 'next/image';
import twemoji from 'twemoji';

const U200D = String.fromCharCode(0x200d);
const UFE0Fg = /\uFE0F/g;

function Twemoji({
  emoji,
  ext = 'svg',
  width = 72,
  height = 72,
}: {
  emoji: string
  ext?: 'svg' | 'png'
  width?: number
  height?: number
}) {
  const HEXCodePoint = twemoji.convert.toCodePoint(
    emoji.indexOf(U200D) < 0 ? emoji.replace(UFE0Fg, '') : emoji,
  );

  return (
    <NextImage
      src={`https://twemoji.maxcdn.com/v/latest/${ext === 'png' ? '72x72' : 'svg'}/${HEXCodePoint}.${ext}`}
      width={width}
      height={height}
      alt={emoji}
      loading="lazy"
      draggable={false}
    />
  );
}

export default React.memo(Twemoji);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment