I have this setState to control my panel open/close state somewhat similar to this post here. And I'm trying to open one panel at one time so there will be only one true value in the state.
Here's my code:
// Parents component
const [show, setShow] = useState({
1 : false, // id=1 when passed to child component (using another props but
2 : false, // dont worry, I'm passing it correctly)
3 : false, // id=3 and so on...
4 : false,
5 : false,
6 : false
})
//Child component
// id is used to check which panel is in open/close state
const handleShowPanel = (id) => {
const val = !props.show
// props.setShow(prev => ({...prev, [key[0].charCodeAt(0)]: false}))
props.setShow(prev => ({...prev, [id] : val})) //this is the one i'm using
// props.setShow(prev => Object.fromEntries(Object.entries(prev).map(([k, v]) => Number(k) !== id ? [k, !v] : [k, false])))
}
The code that I'm using works perfectly fine opening and closing one panel by another one.
Here's a picture for better illustration, let's say first I opened the Panel 1, after that when I clicked Panel 2 I want to close Panel 1 while opening Panel 2. So I will have to set all other values to false except the panel that I'm opening. It is like accordian mode in ant design