Search code examples
reactjsreact-hooksreact-propsreact-state

Pass child state to parent to open and close menu component


I have been trying for hours now and i can't get it to work, please help me out here.

I don't understand what is wrong with my code... An example below

// Parent component
export default (props) => {
    const [status, setStatus] = useState(false)

    const handleChildStatus = (childStatus) => {
        console.log(childStatus)
        setStatus(childStatus)
    }

    return (
        <header>
            <Menu
                childstatus={handleChildStatus}
                status={status}
                className={
                    status ? 'menu-wrapper show-menu' : 'menu-wrapper hide-menu'
                }
            />
            <div className="open-menu" onClick={() => setStatus(true)}></div>
        </header>
    )
}

// Menu component
export default (props) => {
    const [status, setStatus] = useState(false)
    return (
        <div
            childstatus={props.childstatus(status)}
            className={props.className}
        >
            <div onClick={() => setStatus(false)}>
                <img src={CloseMenu} alt="close-menu" />
            </div>
        </div>
    )
}

So with the code below I want to toggle the Menu component on and off.

In parent there is a menu button to open it, in the Menu component itself there is a button to close it. The state is not flowing correctly between the 2 components and i would like to get some help on how to achieve this logic.

Thanks in advance!


Solution

  • There is no need of maintaining status in child component you can handle it from parent's status variable like show below:

    // Menu component
    export default (props) => {
        return (
            <div
                className={props.className}
            >
                <div onClick={() => props.childstatus(false)}> // on click call parent's handleChildStatus function so in next render it will give hide class
                    <img src={CloseMenu} alt="close-menu" />
                </div>
            </div>
        )
    }