react-burger-menu icon indicating copy to clipboard operation
react-burger-menu copied to clipboard

Consider adding a prop for close on clicking item

Open anasik opened this issue 5 years ago • 6 comments

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.

anasik avatar Nov 25 '20 17:11 anasik

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.

negomi avatar Nov 26 '20 21:11 negomi

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?

boverU avatar Dec 02 '20 11:12 boverU

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>

negomi avatar Dec 03 '20 03:12 negomi

@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

boverU avatar Dec 03 '20 07:12 boverU

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

negomi avatar Dec 03 '20 07:12 negomi

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

boverU avatar Dec 03 '20 14:12 boverU