I am getting state= false on desktop size when there is no toggle option as it is defined as false initially. Because of this, no menus are showing. I want this functionality only when the website is opened on mobile, not on desktop.
const Navbar = () => {
const [isMenuOpen, setIsMenuOpen] = useState(false);
const toggle = () => setIsMenuOpen(!isMenuOpen);
const ref = useRef();
useEffect(() => {
const checkIfClickedOutside = (e) => {
if (!ref.current?.contains(e.target)) {
setIsMenuOpen(false);
}
};
document.addEventListener("mousedown", checkIfClickedOutside);
return () => {
document.removeEventListener("mousedown", checkIfClickedOutside);
};
}, []);
return (
<>
<header>
<nav>
<div className="nav">
<div className="nav-brand">
<Link to="./" className="text-black">
Website
</Link>
</div>
<div ref={ref}> // <-- ref to this containing div
<div className="toggle-icon" onClick={toggle}>
<i
id="toggle-button"
className={isMenuOpen ? "fas fa-times" : "fas fa-bars"}
/>
</div>
{isMenuOpen && (
<div className={isMenuOpen ? "nav-menu visible" : "nav-menu"}>
....
</div>
)}
</div>
</div>
</nav>
</header>
</>
);
};