I'm having trouble with creating a hamburger button menu. The issue I'm facing is that when I click the button, nothing happens. Even though I can log something in the toogleHamburger
function and see it in the console, the styling does not change as expected. If I don't use an eventListener in the useEffect, it throws a
Cannot read property 'addEventListener' of null
error. My goal is to change the styling when the button is clicked. I am utilizing module.scss for the classnames.
Nav.js
const Nav = () => {
useEffect(()=>{
var navbar = document.querySelector(".navbar")
var ham = document.querySelector(".ham")
const toggleHamburger = () => {
navbar.classList.toggle("showNav")
ham.classList.toggle("showClose")
}
ham.addEventListener("click", toggleHamburger)
var menuLinks = document.querySelectorAll(".menuLink")
menuLinks.forEach(
function(menuLink) {
menuLink.addEventListener("click", toggleHamburger)
menuLink.removeEventListener("click", toggleHamburger)
}
)
})
return (
<div>
<button className={`${styles.ham} ham`}></button>
<nav className={`${styles.navbar} navbar`}>
<ul>
<li><a className={`${styles.menuLink} menuLink`} href="#">Home</a></li>
<li><a className={`${styles.menuLink} menuLink`} href="#">Profile</a></li>
<li><a className={`${styles.menuLink} menuLink`} href="#">About</a></li>
<li><a className={`${styles.menuLink} menuLink`} href="#">Contacts</a></li>
</ul>
</nav>
</div>
);
};
_nav_module.scss
.ham {
position: absolute;
z-index: 1000;
top: 20px;
right: 20px;
width: 36px;
height: 36px;
border: none;
cursor: pointer;
background-color: transparent;
background-image: url("https://ljc-dev.github.io/testing0/ham.svg");
background-size: 100%;
}
.showClose {
background-image: url("https://ljc-dev.github.io/testing0/ham-close.svg");
}
.navbar {
position: absolute;
top: 0;
left: 0;
background: black;
width: 100vw;
height: 100vh;
overflow: hidden;
color: white;
transform: translateY(-100%);
transition: transform 0.2s ease;
}
.showNav {
transform: translateY(0);
}
.navbar ul {
width: 100%;
height: 100%;
list-style: none;
display: flex;
flex-flow: column nowrap;
justify-content: space-evenly;
align-items: center;
}
.navbar ul li a {
color: white;
padding-bottom: 10px;
border-bottom: 2px solid black;
text-decoration: none;
font-family: 'Open Sans', sans-serif;
font-size: 1.2rem;
}
.navbar ul li a:hover, .navbar ul li a:focus {
border-bottom: 2px solid white;
}