Home > Back-end >  Toggle accordion items
Toggle accordion items

Time:10-13

I have a React Js accordion, when i click an item, the panel opens, to close it you have to click on another item, i need to add the possibility of closing the active panel after clicking the AccButton

Here is my code :

const { active, setActive } = useContext(AccordionContext)

const eventHandler = (e, index) => {
    e.preventDefault();
    setActive(index);
}

return (
    <AccItem id={props.index}>
        <AccButton
            onClick={(e) => eventHandler(e, props.index)}
            aria-expanded={ active === props.index ? 'true' : 'false' }
            aria-disabled={ active === props.index ? 'true' : 'false' }
        >
            <AccItemTitle>
                {props.description}
            </AccItemTitle>
        </AccButton>

        <AccPanel elWidth={props.elWidth}>
            <PanelToggle toggle={active === props.index}></PanelToggle>
        </AccPanel>

    </AccItem>
)

CodePudding user response:

You could try to add a check if active !== index and otherwise set active to null. Like this:

const eventHandler = (e, index) => {
    e.preventDefault();
    setActive(index !== active ? index : null);
}
  • Related