I have a React Js accordion, when i click an item, the panel opens, to close it you have to click the same item or another item, i need the keep the first item opened in the beginning.
The method eventHandler gets the id of each item of the accordion, these items are fetched from an API, everytime i click an item i get the id of the item, but when the component mounts the console.log(active) returns null
I need to get the id of the first item, because the first index is not gonna be 0 so useState(0) won't help, any ideas how to do so?
Here is my code :
const { active, setActive } = useContext(AccordionContext)
const eventHandler = (e, index) => {
e.preventDefault();
setActive(index !== active ? index : null);
}
return (
<div id={props.index}>
<button
onClick={(e) => eventHandler(e, props.index)}
aria-expanded={ active === props.index ? 'true' : 'false' }
aria-disabled={ active === props.index ? 'true' : 'false' }
>
<span>
{props.description}
</span>
</button>
<div>
<div toggle={active === props.index}></div>
</div>
</div>
)
And here is the AccordionContext
const AccordionWrapper = (props) => {
const [active, setActive] = useState(null);
console.log(active)
return (
<AccordionContext.Provider
value={{
active, setActive
}}
>
<AccWrapper>
{props.children}
</AccWrapper>
</AccordionContext.Provider>
)
}