How do you make a custom React component keyboard accessible?
Short answer
A custom component built from a div or span does not get keyboard behavior automatically the way a real button does. To fix this you add tabIndex so it can be focused, and an onKeyDown handler so pressing Enter or Space triggers the same action as a click.
Advertisement
AModel answer
A custom component built from a div or span does not get keyboard behavior automatically the way a real button does. To fix this you add tabIndex so it can be focused, and an onKeyDown handler so pressing Enter or Space triggers the same action as a click.
function CustomButton({ onClick, children }) {
return (
<div
role="button"
tabIndex={0}
onClick={onClick}
onKeyDown={(e) => {
if (e.key === 'Enter' || e.key === ' ') onClick();
}}
>
{children}
</div>
);
}Real-world example
A design team builds a custom styled button using a div for a unique look, and adds keyboard support so users who cannot use a mouse can still activate it with the Enter key.
Likely follow-ups
- Why is it usually simpler to just use a real button element instead of building a custom one?
- How do you manage focus order across a whole page?
Related topics