- Published on
Understanding the `jsx-a11y/click-events-have-key-events` Error
- Authors
- Name
- hwahyeon
jsx-a11y/click-events-have-key-events
To sum up, this error occurs when a tag with a click event is not designed to be accessible to users who rely on the keyboard. A11Y refers to web accessibility, and the goal of accessibility is to design web pages in a way that all users can use them.
Users with visual impairments or mobility disabilities often navigate the web using only a keyboard, using the Tab
key to access elements and the Enter
or Space
keys to replace mouse clicks. However, the following code cannot be accessed using the Tab
key, which causes the jsx-a11y/click-events-have-key-events
error.
<div onClick={handleClick}>Click me</div>
Since only onClick
is set and the keyboard cannot be used for interaction, this error occurs.
Solution
- Use the
button
tag
<button onClick={handleClick}>Click me</button>
The <button>
tag inherently supports keyboard accessibility. You can navigate to it using the Tab
key, and pressing the Enter
or Space
keys will automatically trigger the click event. This is a feature provided by the HTML5 standard and is supported by all modern browsers.
Additionally, assistive technologies like screen readers automatically recognize the <button>
tag as a button without the need for additional ARIA attributes. ARIA (Accessible Rich Internet Applications) is a standard aimed at improving web accessibility by making clear what role each element plays. The <button>
tag inherently includes the role="button"
attribute, allowing screen readers to help users understand the function of the button based on this information.
- When using
div
orspan
<div
role="button"
tabIndex={0}
onClick={handleClick}
onKeyDown={(e) => {
if (e.key === 'Enter') handleClick(e)
}}
>
Click me
</div>
When using <div>
or <span>
, ARIA roles are not automatically set, so you need to explicitly add role="button"
. You should also set tabIndex={0}
to allow the element to receive keyboard focus, and use onKeyDown
to handle the Enter
key so that keyboard users can trigger the click event as well. While these features are built into the <button>
tag, if you need to use static elements like <div>
or <span>
, you can manually implement accessibility like this.