I am working on making an accordion keyboard-accessible. Currently clicking on an item will expand the item. Clicking on the same item will close it. If you have one open and click a different item, the previous will close and the new will open. I want the user to be able to tab through the accordion, and anchors in the item if they are present, meaning it will expand when tabbed onto and close when tabbed out of. I am also using styled components, if that matters.
//isActive determines if the accordion is expanded
//activeClass is to change css state
const isActive = active === id;
const activeClass = isActive ? "active" : null;
//changes the active accordion
const toggleAccordion = () => {
if (isActive) {
setActive(null);
} else {
setActive(id);
}
};
return (
<Item onFocus={toggleAccordion} onBlur={() => setActive(null)} tabIndex={0}>
<Title onClick={toggleAccordion} active={activeClass}>
<Container>{title}</Container>
</Title>
<Content active={activeClass}>{content}</Content>
</Item>
I've tried a handful of things I could think of, like only triggering the click if it's already expanded (to close the accordion) but it would never close since clicking on it also causes it to become focused.
Currently the focus and click fight each other, making the first click expand/close immediately, but the second works fine.
Is it also possible to navigate using keyboard arrows? And would it be simpler if the user has to hit an enter button to open the accordion rather than having it auto-open/close?