I am trying to make my navbar responsive for mobile in Vite reactjs using useRef hook but its not wokring.
I tried to use useRef hook to make it responsive by toggling classList "responsive_nav" on nav tag in my NavBar component. I have 2 buttons from react icons, FaTimes and FaBars for navbar in mobile, and the classes are toggled with useRef().
here's my NavBar component:
import React, { useRef } from "react";
import "../styles/styles.css";
import { Link } from "react-router-dom";
import { FaBars, FaTimes } from "react-icons/fa";
function NavBar() {
const navRef = useRef();
const showNavBar = () => {
navRef.current.classList.toggle("responsive_nav");
};
return (
<>
<nav ref={navRef}>
<div className="itemL">
<Link to="#">mjshubham21</Link>
</div>
<div className="itemR">
<ul>
<li>
<Link to="#">Home</Link>
</li>
</div>
</nav>
<button className="nav-btn nav-close-btn" onClick={showNavBar}>
<FaTimes />
</button>
<button className="nav-btn" onClick={showNavBar}>
<FaBars />
</button>
</>
);
}
export default NavBar;
//Here's CSS for Navbar:
nav {
display: flex;
justify-content: space-between;
align-items: center;
padding: 1.1rem 0.8rem;
height: 1.1rem;
z-index: 200;
}
.nav-btn {
padding: 0.5rem;
cursor: pointer;
background: transparent;
border: none;
outline: none;
position: absolute;
top: 2rem;
right: 2rem;
visibility: hidden;
opacity: 0;
font-size: 1.5rem;
}
@media (max-width: 450px) { //Is my media query correct or shall it change the unit??
.nav-btn {
visibility: visible;
opacity: 1;
}
nav {
position: fixed;
top: 0;
left: 0;
height: 100vh;
width: 100vw;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 1.5rem;
transition: 250ms;
transform: translateY(-100vh);
}
nav .responsive_nav {
transform: none;
}
.nav-close-btn {
position: absolute;
top: 2rem;
right: 2rem;
z-index: 9999;
}
nav a {
font-size: 2rem;
}
}