Im using react with typescript. I am a little confused as to how can i pass ‘global’ parent state to list of its childrens?
For example there is ‘Parent’ and list of ‘Child’ components, i want to change parent state and set it to its child components:
interface ParentProps {
childs: ChildProps[]
}
interface ChildProps {
isOpen: boolean
}
const ParentComponent: FC<ParentProps> = (parentProps: ParentProps) => {
const [globalState, setGlobalState] = useState(false);
const handleClick = () => {
setOpenState(!changeOpenChildsState);
// So here i should something like iterate over all childrens and change its state but how ?
}
return (
<>
<button onClick= { handleClick } />
parentProps.childs.map(child => {
<Child isOpen={ child.isOpen } />
})
</>
)
}
const Child: FC<ChildProps> = (childProps: ChildProps) => {
const [openState, setOpenState] = useState(childProps.isOpen);
const handleChildClick = () => {
setOpenState(!openState);
}
return (
<div>
<button onClick= { handleChildClick } />
<div> is child open ? { openState } </div>
</div>
)
}
2
Answers
Without using
useContext
anduseReducer
to create state management in your application, maybe something like this could work where you populate a reference on your parent with the functions you need to call. When each of the child components mounts, it passes its setter function to its parent:If what you want is to have a "toggle all" button, you can just use
useEffect
and toggle all of the children to the global value when the global state is passed as a prop: