This is a much more simpler question which will eventually solve my question here. So how do I change this show which is in Component A from Component B?
Component A:
const [show, setShow] = useState({
1 : false,
2 : false,
3 : false,
4 : false,
5 : false,
6 : false
})
Component B:
const handleShowPanel = (id) => {
//how do I reset them here
}
I don't fully understand the question, but I'll try to write some code on what I undertstand.
function Parent() {
const panels = [0,1,2,3,4,5]
const [panelsShowing, setPanelsShowing] = useState({
0: false,
1: false,
2: false,
3: false,
4: false,
5: false,
})
const togglePanelShowing = useCallback((index) => {
setPanelsShowing(prevState => ({
...prevState,
[index]: !prevState[index]
}))
},[setPanelsShowing])
return (
<div>
{panels.map((onePanel, panelIndex) => {
return (<Panel
isShowing={panelsShowing[panelIndex]}
togglePanelShowing={() => togglePanelShowing(panelIndex)}
/>)
})}
</div>
)
}
const Panel = ({ isShowing, togglePanelShowing }) =>
isShowing ? (
<div>
<button onClick={togglePanelShowing}>Toggle!</button>
</div>
)
: null
I also see that you wrote that you actually want to have the toggle function in the child, that is simple, pass the setShow to the child component and recreate the toggle function inside it.
<Panel setPanelsShowing={setPanelsShowing} />
another thing that I want to say, if the show Object is all you have and actually you don't have an array of elements, then you can still use the same toggle show function but instead of mapping through panels you would map with Object.entries of the show object and the key would be the number and the value would be the boolean if it's showing or not.
for example:
const toggleShowing = (number) => {
setPanelsShowing(prevState => ({
...prevState,
[number]: !prevState[number]
}))
}
// in the JSX return:
Object.entries(panelsShowing).map(([number, isShowing]) => (<Panel isShowing={isShowing} toggleShowing={() => toggleShowing(number)}/>))
maybe if you added more to your question I could understand it better, but from what I understand you have an array of some elements and you want to decide if the element is showing based on the index. Or you have an object with the keys being the number and the value being wether it is showing or not.