How to fix click-events-have-key-events?

Last updated:

Some users rely on keyboard navigation only while navigating the web. To ensure accessibility for these users, the Eslint plugin 'jsx-a11y' and similar plugins in other frameworks give the linting error click-events-have-key-events.

How to fix click-events-have-key-events linting error?

The easiest way to make a clickable element usable for keyboard users is to use native HTML elements instead of using <div onClick={...}/> . Native HTML elements which are accessible by default are button and a .

If it's not possible to use native clickable HTML elements, you should use one of the following techniques to add a keyboard listener:

<div onClick={handler} onKeyDown={handler} tabIndex="0" role="button">
# Or
<div onClick={handler} onKeyUp={handler} tabIndex="0" role="button">
# Or
<div onClick={handler} onKeyPress={handler} tabIndex="0" role="button">

Note the tabIndex="0" and role="button" which are important for accessibility!

There are 6 keyboard WCAG Criteria

Does your website comply with all of them?

Is using a keyboard event listener sufficient for an accessible button?

There are more things needed to make a clickable element accessible:

  1. A clickable element should be focusable for keyboard users. To make an element focusable, you should add a tabIndex="0" attribute.
  2. Screen readers and other technologies need to know the role of the clickable element. You can do this by adding the role="button" attribute.

Conclusion

Fix the click-events-have-key-events linting error in your React, Angular, Vue or Svelte application by using an HTML element that is clickable as per the HTML specification. If that is not possible, add keyboard event listener, a role="button" attribute and a tabIndex attribute.

For more info see:

Share this article

Author Arjan Schouten

As the founder of ExcellentWebCheck, I'm very passionate about accessibility and ensuring equal access to information and services online. With the current speed of digitalization, it is crucial to make sure that everyone has access to important goods and services such as healthcare, financial services, education, and government resources, regardless of their abilities. By advocating for inclusive design principles and leveraging cutting-edge technologies, we aim to create digital environments that are not only compliant with accessibility standards but also intuitive and user-friendly for all individuals.

Was this article helpful?

Checkout the ExcellentWebCheck services

ExcellentWebCheck's goal is to improve the online user experience. The tools of ExcellentWebCheck help to detect and improve usability problems on your website.