Search code examples
reactjschakra-ui

Using the Chakra-UI useDisclosure hook on both a parent and child component


I am trying to use the Chakra UI useDisclosure hook accross two different components. Basically, I have a parent component with a button and a child component with a different button. I want to use onToggle in the parent component and onClose in the child component -- and have BOTH OF THEM control the state of isOpen on the child component. Is this possible? If so, how? Thanks.


Solution

  • You can use the hook useDisclosure inside the parent component, then pass the state isOpen and onClose to your child component:

    function Parent() {
      const { isOpen, onToggle, onClose } = useDisclosure()
    
      return (
        <>
          <Button onClick={onToggle}>Open Drawer</Button>
          <Child isOpen={isOpen} onClose={onClose} /> 
        </>
      )
    }