i have a collabsable sidebar that i'm building with react and some menus have dropdowns, what would be the best approch to collapse the dropdown menus when the sidebar itself is called to collapse i have to boolean's for the sidebar and the menus within the sidebar
this is the basic function that collapses the sidebar
const [open, setOpen] = useState(false) //for the menus
const [collapse, setCollapse] = useState(false) //for the sidebar
function handleCollapse() {
setCollapse(!collapse);
}
i'm calling the function from a button onClick={handleCollapse}
CodePudding user response:
Just add an effect that gets triggered when collapse changes
useEffect(() => {
if(collapse) setOpen(false)
}, [collapse])
btw, you can use functional state update to access previous collapse
:
function handleCollapse() {
setCollapse(prevCollapse => !prevCollapse);
}
CodePudding user response:
I see 2 ways
- Change your state to object
const [state, setState] = useState({ open: false, collapsed: false })
function handleCollapse() {
if (!state.collapsed) {
setState({ open: false, collapsed: true });
} else {
setState({ open: true, collapsed: false });
}
}
useReducer
with a similar functionality as useState
I would avoid useEffect
- it would require state update twice.