Skip to content

Instantly share code, notes, and snippets.

@rushkeldon
Last active May 6, 2025 21:43
Show Gist options
  • Save rushkeldon/0d8d57aff64fd4ef32b10c7c6a63e0d0 to your computer and use it in GitHub Desktop.
Save rushkeldon/0d8d57aff64fd4ef32b10c7c6a63e0d0 to your computer and use it in GitHub Desktop.
A hook to enable keyboard handling on non-interactive elements that are made interactive.
import { useCallback } from 'react';
function isElementDisabled(el: HTMLElement): boolean {
return (
el.hasAttribute('disabled') ||
el.getAttribute('aria-disabled') === 'true' ||
el.getAttribute('data-disabled') === 'true'
);
}
export function useA11yKeysClick() {
const onKeyDown = useCallback((event: React.KeyboardEvent<HTMLElement>) => {
const el = event.currentTarget as HTMLElement;
if (isElementDisabled(el)) return;
const { key } = event;
if (key === 'Enter' || key === ' ') {
event.preventDefault(); // Prevent spacebar scrolling
el.click(); // Fire native click event
}
}, []);
return {
tabIndex: 0,
role: 'button',
onKeyDown,
};
}
function FancyBox() {
return (
<div
{...useA11yKeysClick()}
onClick={() => console.log('Activated')}
aria-disabled="false"
>
I'm interactive
</div>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment