What you could do is to add an event handler to the hamburger menu and close icon to update a local state like open
or close
. Then depending one the state you add or remove a className. Like this:
Style.css
/* When we click the hamburger menu we want to hide the icon */
.hamburger_img.close {
display: none;
}
/* When we click the menu we want to display this icon */
.right-menu.open {
display: block;
}
HeaderMenu.js
const HeaderMenu = () => {
// Adding class name when scrolll
const [openMenu, setOpenMenu] = useState(false);
// Other code here..
// A toggler to update the state when we open or close menu
const toggleMenu = () => setOpenMenu(openMenu => !openMenu);
// Dynamically add 'open' class if the state is true
const getXMarkClassName = () => `right-menu float-right ${openMenu ? 'open': ''}`;
// Dynamically add 'close' class if the state is true
const getHamburgerMenuClassName = () => `hamburger_img ${openMenu ? 'close': ''}`;
return (
<header id="header_menu" className={headerClassName}>
<div className={getHamburgerMenuClassName()} onClick={toggleMenu} >
<img src={require("../images/menu.png")} alt="Menu bar"/>
</div>
<div className={getXMarkClassName()}>
<div className="x_mark_img" onClick={toggleMenu} >
<img src={require("../images/close.png")} alt="Menu Close" />
</div>
<ul>
{/* code here... */}
</ul>
</div>
</header>
);
};
Notice that I added an onClick
handler to the div
to update the state whenever they are clicked. Like wise notice that I call a function to get the className
for both the icon menu and the close icon.
Second Issue
To close the navigation when the route changes you can listen to route changes using useEffect
and then call the toggle()
function. Like this:
import React, { useEffect } from 'react';
import { useLocation } from 'react-router';
function HeaderMenu() {
// Other code here...
const location = useLocation();
useEffect(() => {
console.log("route has been changed, toggle the menu");
if (openMenu) {
toggleMenu();
}
// To scroll up on route change
window.scrollTo(0, 0);
}, [location.pathname]);
// Other code here...
}
Notice I didn't add openMenu
to the list of dependencies in useEffect
alongside location.pathname
. This is because I don't want this useEffect to run anytime the openMenu
state changes only when the route changes. I have an if statement there so if the route changes and the menu wasn't opened, the toggle shouldn't be called.
Hope it helps. You can test it in this codesandbox