Last active
May 6, 2025 21:43
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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, | |
}; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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