DEV Community

Cover image for A simple react a11y Emoji component
Florian Rand
Florian Rand

Posted on • Updated on • Originally published at flrnprz.gitlab.io

A simple react a11y Emoji component

Emojis are cool, right? Everyone ❤️ emojis, but screen readers have a different opinion about the subject.

For those who don't already know, there are two attributes very useful to help screen readers:

aria-label adds a string label to an element, it's useful in cases that the text label is not visible on the screen.

aria-hidden (From MDN):

Adding aria-hidden="true" to an element removes that element and all of its children from the accessibility tree. This can improve the experience for assistive technology users by hiding:

Purely decorative content, such as icons or images.
Duplicated content, such as repeated text.
Offscreen or collapsed content, such as menus.

So, these attributes seems a very good idea to our Emoji component. Let's see it in action:

import React from 'react';

const Emoji = ({label, symbol}) => (
  <span
    className="emoji"
    role="img"
    aria-label={label ? label : ''}
    aria-hidden={label ? 'false' : 'true'}
  >
    {symbol}
  </span>
);

export default Emoji;
Enter fullscreen mode Exit fullscreen mode

If we don't pass a label prop, we want to set aria-hidden to true so screen readers ignore our emoji.

And some use example:

<Emoji label="open book" symbol="📖" /> {timeToRead} min read
Enter fullscreen mode Exit fullscreen mode

Which renders something like this:

<span class="emoji" role="img" aria-label="open book" aria-hidden="false">📖</span>
2 min read
<!-- ... ->
Enter fullscreen mode Exit fullscreen mode

And this is it! Fun isn't it?
Happy ❤️☕️🐑🐧!

Cover image by Lidya Nada @Unsplash

Top comments (0)