I have an open/close component that is applied to multiple sections.
export default function Expand() {
const [open, setOpen] = useState(false);
const expand = () => {
setOpen(!open);
};
Later in my code I have this (EDITED):
{sections.map((item, i) => (
<div key={i}>
<button
onClick={expand}>
<h2>{item.heading}</h2>
And then:
{open && ( <div>Text when you open</div> ) }
Problem is that the multiple sections all open/close when clicking just one section. I need that when you click section one, only section one opens/closes. Then when clicking section two, only section two opens/closes.
I figure that I have to use this
keyword but with my current code I don´t see where to add. Where to add to achieve my goal?
2
Answers
this
keyword is irrelevant here. You cannot use a single state value to keep track of expended state of multiple sections; you need an array of states.Create a custom hook
useExpand
like