React useState boolean issue (functional component)

Viewed 47

I am having trouble with useState and state change in a React Functional Component. I am using an imported package called Menu that takes a prop called "isOpen" - when set to true the Menu (similar to a modal) is displayed.

When I click on the "Close Menu" button that is within the Menu modal, the state for menuOpen changes to false - however, the isOpen prop does not switch from true to false - and therefore the menu does not close. Or else Am I missing something here?

const MenuButton: React.FC<Props> = () => {
  const [menuOpen, setMenuOpen] = useState(false)
  const openMenu = () => {
  setMenuOpen(true)
}

const closeMenu = () => {
  setMenuOpen(false)
}

 return (
 <Menu buttonNode={<Button onClick={openMenu}>Open 
 Menu</Button>} isOpen={menuOpen}>
   <Box>
     <Text>Menu Heading</Text>
     <Button onClick={closeMenu}>Close Menu</Button>
   </Box>
 </Menu>
 )
}
1 Answers

It's definitely a problem with 'pcln-menu' package as it's developers don't use the single source of truth principle when designing component's state.

You should pass menu content as renderContent property to obtain handleClose callback. Try this:

const MenuButton = () => {
  const [menuOpen, setMenuOpen] = useState(false);
  const openMenu = () => {
    setMenuOpen(true);
  };

  return (
    <Menu
      buttonNode={<Button onClick={openMenu}>Open Menu</Button>}
      isOpen={menuOpen}
      renderContent={({handleClose}) => (
        <Box>
          <Text>Menu Heading</Text>
          <Button onClick={handleClose}>Close Menu</Button>
        </Box>
      )}
    ></Menu>
  );
};
Related