negomi / react-burger-menu

:hamburger: An off-canvas sidebar component with a collection of effects and styles using CSS transitions and SVG path animations
http://negomi.github.io/react-burger-menu/
MIT License
5.05k stars 586 forks source link

Consider adding a prop for close on clicking item #423

Open anasik opened 3 years ago

anasik commented 3 years ago

I know this is possible right now and there's even an example that shows how to do it but it's a ittle inefficient to have to add an onclick to each menu item. It would be cool to have a prop that allows you to enable/disable this.

negomi commented 3 years ago

Hi @anasik,

Do you mean something like a closeOnItemClick boolean prop, that would add an click handler behind the scenes to close the menu on any item click?

That sounds reasonable, I'd accept a PR for it. Will leave this open.

boverU commented 3 years ago

I have FC with state and handler like below const [isMenuOpen, handleMenu] = useState(true) const handleCloseMenu = () =>{ handleMenu(false) }

<Menu isOpen = {isMenuOpen}> <CustomLink onClick = { history.push("/home") handleCloseMenu}>

<CustomLink onClick = { history.push("/work") handleCloseMenu}> </Menu>

This doesnt work correctly, when clicking to Link it closes only once. Think that is because when I click to Burger Button it doesnt triggering handleMenu. But how it opens ?) How can I track it? Or it works only with class components?

negomi commented 3 years ago

Hey @boverU,

You have the right idea, but the code above is invalid because you need to pass functions to the onClick handlers, and also call handleCloseMenu by putting parentheses after it (like this: handleCloseMenu()).

Try this:

const [isMenuOpen, handleMenu] = useState(true);

const handleCloseMenu = () => {
  handleMenu(false);
};

<Menu isOpen={isMenuOpen}>
  <CustomLink
    onClick={() => {
      handleCloseMenu();
      history.push('/home');
    }}
  />
  <CustomLink
    onClick={() => {
      handleCloseMenu();
      history.push('/work');
    }}
  />
</Menu>
boverU commented 3 years ago

@negomi Sorry, since I`m not allowed to make copies of code directly I typed it manually and forgot about calling function paranthesis. Can you check out this one on codesandbox.io, the problem still having the place - https://codesandbox.io/s/frosty-dewdney-zotlj?file=/src/Navbar.js and closes sidemenu only once. Thank you

negomi commented 3 years ago

Oh I see! Now the issue is that you need to add the onStateChange prop, so your isMenuOpen variable always stays in sync.

I adapted your example to make it work: https://codesandbox.io/s/charming-breeze-u1tck?file=/src/Navbar.js

boverU commented 3 years ago

Thanks man!) You saved a lot of my time!)