Reputation: 131
I'm trying to code a toggle menu in ReactJS in a way that I can understand. I understand that my code is a newbie and I need some help to understand what I'm doing wrong here, I'm stuck in this for almost 12 hours.
With the function display(), I'm trying to add a new className to the nav so would be "topnav responsive" so in this way, I could activate the new style within the @media CSS to make a responsive menu.
function Menu() {
const [showMenu, setMenu] = useState();
function display() {
const setMenu = () => {
let toggle = document.querySelector(".topnav");
if (toggle.className === "topnav") {
toggle.className += " responsive";
} else {
toggle.className = "topnav";
}
};
}
return (
<header>
<div className="container container-nav">
<div
onClick={() => {
display();
}}
className="logo"
>
<img src={logo} alt="" />
</div>
<nav className="topnav">
<ul>
<li className="icon">
<img src={burgerMenu} alt="" />
</li>
<li>
<a href="">Home</a>
</li>
<li>
<a href="">About</a>
</li>
<li>
<a href="">Projects</a>
</li>
<li>
<a href="">Contact</a>
</li>
</ul>
</nav>
</div>
</header>
);
}
** CSS **
@media (max-width: 600px) {
.topnav.responsive {
position: relative;
}
.topnav.responsive .icon {
position: absolute;
right: 0;
top: 0;
}
.topnav.responsive a {
float: none;
display: block;
text-align: left;
}
}
Upvotes: 1
Views: 1401
Reputation: 976
I think maybe you were trying to do something like this?
import { useState } from 'react';
function Menu() {
const [showMenu, setMenu] = useState();
function display() {
setMenu(value=>!value)
}
return (
<header>
<div className='container container-nav'>
<div
onClick={display}
className='logo'
>
<img src={logo} alt='' />
</div>
<nav className={`topnav${showMenu?' responsive':null}`}>
<ul>
<li className='icon'>
<img src={burgerMenu} alt='' />
</li>
<li>
<a href=''>Home</a>
</li>
<li>
<a href=''>About</a>
</li>
<li>
<a href=''>Projects</a>
</li>
<li>
<a href=''>Contact</a>
</li>
</ul>
</nav>
</div>
</header>
);
}
Rule of thumb is you should avoid the DOM API most of the time when using React. If you are doing something like document.querySelector(x)
, you might actually be wanting to use a Ref (https://reactjs.org/docs/refs-and-the-dom.html).
This time, however, a simple condition will suffice.
Upvotes: 1