Home > OS >  What should i do to automatically close navbar when i click to a page?
What should i do to automatically close navbar when i click to a page?

Time:02-03

can you help me what and where should i put to close the navbar when i navigate to other pages?

It only closes when i click to the close button itself.

Here is my code to the navbar:

import { useRef } from "react";
import { FaBars, FaTimes } from "react-icons/fa";
import "../Styles/main.css";
import { NavLink } from "react-router-dom";
import FacebookIcon from '@mui/icons-material/Facebook';
import InstagramIcon from '@mui/icons-material/Instagram';
import logo from "./img/logojobb.png";

function Navbar() {
    const navRef = useRef();
    const showNavbar = () => {
        navRef.current.classList.toggle("responsive_nav");
    };
    return (
        <header>
            <img src={logo} alt="logo" style={{
                height: 'inherit',
            }}/>
            <nav ref={navRef}>
            <NavLink  to="/">Kezdőlap</NavLink>
            <NavLink  to="/courses">Órák</NavLink>
            <NavLink  to="/blog">Blog</NavLink>
            <NavLink  to="/rental">Terem bérlés</NavLink>
            <NavLink  to="/events">Rendezvények</NavLink>
            <NavLink  to="/contact">Kapcsolat</NavLink> 
                <a className="footersocial" href="https://www.facebook.com/julialaszlo.liafit/" target="_blank" rel="noreferrer"><FacebookIcon></FacebookIcon></a>
                <a className="footersocial" href="https://www.instagram.com/liafit_movar/" target="_blank" rel="noreferrer"><InstagramIcon></InstagramIcon></a>                 
                <button
                    className="nav-btn nav-close-btn"
                    onClick={showNavbar}>
                    <FaTimes />
                </button>
            </nav>
            <button className="nav-btn" onClick={showNavbar}>
                <FaBars />
            </button>
        </header>
    );
}
export default Navbar;

CodePudding user response:

One option (If I presume you nav to other pages via button) is to simply call CloseNavbar (Or whatever you have there) on onclick on all the buttons that nav to the other page. You can have multiple onclick functions by simply adding a comma between functions, like so:

<button onclick="CloseNavbar(), NavToPage(Page)">Here is a button!</button>

This should work as you expect.

  • Related