DEV Community

Thomas Alcala Schneider
Thomas Alcala Schneider

Posted on

Emojis in Svelte 3

Hey!

So today, let's make an emoji component in Svelte 3. It's fairly simple. Our objective is to be able to write something like below, and it'll show the emoji. We also want to be careful that the accessibility attributes are there.

<Emoji symbol="" label="Hi!" />
Enter fullscreen mode Exit fullscreen mode

Let's start by writing our Emoji component, and call it Emoji.svelte, with the following content:

<script>
  export let label;
  export let symbol;
</script>

<style>
</style>

<span
  className="emoji"
  role="img"
  aria-label={label ? label : ""}
  aria-hidden={label ? "false" : "true"}
>
{symbol}
</span>
Enter fullscreen mode Exit fullscreen mode

Quick explanation:

  • The component will be a span
  • It has a symbol and a label attribute, so it's a11y-compliant
  • The aria is hidden if there's no label (but you should always put one)
  • The symbol is the actual emoji, and will be displayed as a child/inner HTML of the span
  • Inside the script tag, we make the label and symbol variables available
  • I am leaving a style tag, so you can add CSS in there if you want

And that is it! I You just have to import the component like so, in another component's script tag:

<script>
  import Emoji from '../components/Emoji.svelte';
</script>
Enter fullscreen mode Exit fullscreen mode

... Then use the Emoji tag as described in the first code block, and that's it!

You still have to copy/paste the emoji character from somewhere and insert it in the symbol attribute of the Emoji tag. If you are on Mac OS, I recommend the lightweight qmoji by Jared Forsyth, but there's a bunch of those emoji apps for any OS.

Talk to y'all soon!

Top comments (1)

Collapse
 
ekafyi profile image
Eka

Good idea! In React (for example) we have react-a11y lint tool that warns us about common a11y issues, including inaccessible emoji. Haven't seen similar tool for Svelte, so this component will be helpful.