Open anasik opened 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.
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?
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 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
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
Thanks man!) You saved a lot of my time!)
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.