How To Collapse Only One Div When Using React And Map
I'm trying to create a dynamic menu using React and I'm struggling to implement the collapse functionality. I start by mapping each MenuItem using a Json object which works fine. A
Solution 1:
Your "open" variable should be an empty object.
const [open, setOpen] = React.useState({});
Then on the handleClick function you create a new field that has "id" as key.
function handleClick(id) {
setOpen((prevState => ({...prevState, [id]: !prevState[id]}))
}
Then use that as the "open" prop.
<Collapse in={open[postData.id]}>
<div key={postData.id} id="example-collapse-text" className="collapsedText">
{postData.text}
</div>
</Collapse>
Keep in mind that when you want to access the actual state, you always want to do this:
const [state, setState] = useState(true)
setState(prevState => !prevState)
And never
const [state, setState] = useState(true)
setState(!state) // <-- THIS IS BAD
Post a Comment for "How To Collapse Only One Div When Using React And Map"