Is there a way for the navbar to close automatically when I navigate to a new page?

Could you assist me with figuring out where and what to add in order to close the navbar when navigating to other pages?

Currently, it only closes when I click on the close button itself.

Below is the code for 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="/">Home</NavLink>
            <NavLink  to="/courses">Courses</NavLink>
            <NavLink  to="/blog">Blog</NavLink>
            <NavLink  to="/rental">Rental</NavLink>
            <NavLink  to="/events">Events</NavLink>
            <NavLink  to="/contact">Contact</NavLink> 
                <a className="footersocial" href="https://www.facebook.com/example" target="_blank" rel="noreferrer"><FacebookIcon></FacebookIcon></a>
                <a className="footersocial" href="https://www.instagram.com/example" 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;

Answer №1

If you usually navigate to other pages using buttons, one approach is to easily trigger the CloseNavbar function (or its equivalent in your code) by adding an onclick event to all the buttons that lead to another page. You can attach multiple onclick functions by separating them with commas, like this:

<button onclick="CloseNavbar(), NavToPage(Page)">Click here for a button!</button>

By following this method, the functionality should perform as intended.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is causing JS to malfunction and preventing App Scripts from running `doGet()` when using either `e` or `event` as parameters?

Following a Basic Web App video last night, I meticulously followed every step until the very end where things started to go wrong. Today, I decided to start from scratch and recreate it all. Despite weeks of coding practice, I can't seem to figure ou ...

What is the best way to store chat messages in a React application?

My idea for a chat application using React involves saving chat messages in localStorage. Below is the code snippet that illustrates this functionality: const [textMessages, setTextMessages] = useState([]); const [textValue, setTextValue] = useState(' ...

New to React and struggling with updating the DOM

Upon receiving a React project, I am faced with the task of performing a complex state update on my DOM. Here is how my component looks: /** @jsx jsx */ import { jsx } from '@emotion/core'; import { Typography } from '@material-ui/core&ap ...

Issue encountered while generating dynamic Routes using the map function

When attempting to dynamically use Route from an array, I encounter an error. Warning: Incorrect casing is being used. Use PascalCase for React components, or lowercase for HTML elements. The elements I am utilizing are as follows: const steps = [ { ...

Preserve the information within

Recently, I encountered an issue with a file that generates HTML and adds it to a PHP string using a buffer. Here's the code snippet: <?php ob_start(); ?> <table> <tr> <td>Content</td> </tr> ...

When filling options within an optgroup in a selectbox, the data for each option may override one another

UPDATE: I made a change in my code: $('select[name=productSelect]').setOptions(["All products|ALL", "Products visible to all|VISIBLETOALL=1"]); I updated it to: $('select[name=productSelect]').prepend(["All products|ALL", "Product ...

NextJS14 experiencing a duplication issue with toast notifications

After upgrading to the latest NextJS version, I encountered a problem with rendering toast notifications using react-hot-toast. The challenge arose from the fact that these notifications could not be displayed in server components. As a workaround, I crea ...

What is the best way to modify a newly added element using jQuery?

When a user clicks a button on my screen, a new template is loaded dynamically using jQuery's .load() method. This transition adds new HTML to the page that was not present when the script initially loaded: (function($) { $('.go').on("c ...

What is the best method for inserting space between two divs?

I need to create more space between the last two cards and the image at the bottom, but this spacing should increase as I resize the browser window. Can anyone help me with this? https://i.stack.imgur.com/rq9t2.png https://i.stack.imgur.com/tOikx.png Th ...

Having trouble getting a dropdown menu to function properly with jQuery

Within my project, I have implemented a menu that transforms into a dropdown menu for smaller screens. Below is the HTML code for this functionality: <select> <option value="index.php" id="home">Home</option> <option value="about ...

"I am looking for a way to retrieve dynamic data from a (click) event in Angular. Can

Within my component, I have a video loaded in an i tag on a click event. The challenge is accessing the video ID from the video.component.ts file in order to dynamically load a new video. The solution has been elusive so far. <li *ngFor="let video of c ...

What is causing my nested class to be treated as a sibling rather than a child in HTML code

I have been searching for a clear answer to my query, but haven't found one yet. In my HTML script, I have nested divs structured like this: <ul id="navbar"> <li><a href='#' class='dropdown'>Rules</a> ...

What are the steps involved in converting a MERN application into a desktop application?

As a beginner in front-end application development, I recently created a MERN application in React with separate frontend and backend parts. Everything is working smoothly, but now I want to convert it into a desktop application that can run independently ...

Interactive front end design for decision trees

On the front end, I aim to enable users to influence the outcome of a Decision Tree based on their selections. For my Django-React App, I have adopted the style and tree example from the codeplayer. You can find it here: I am tasked with creating an unor ...

downsides of scrolling text functionality

Sure, it may seem evil. But what makes it so? Is it because all browsers support it? Which aspx asp.net controls are restricted in this tag? What are the reasons for avoiding this tag? ...

Updating the count property of an object using setState in React

I have an array of integers ranging from 0 to 6 as my input. My goal is to create an object that gives the count of each number in the array. edition = [6, 6, 6, 1, 1, 2]; const [groupedEdition, setGroupedEdition] = useState([{"0": 0, "1&quo ...

Having trouble getting two form fields to align horizontally in CSS

I am trying to arrange two form fields side by side horizontally, but I am having an issue where the second field is slightly lower than the first field. I am currently using display:inline-block in the CSS to achieve the horizontal alignment. Below is th ...

Flexbox isn't lining up items horizontally as expected

I have been researching flexbox and it seems like it should display in a horizontal row by default. However, no matter what I try, I can't seem to get it to work as expected. I've included the code below. When I remove "display: flex;" from the C ...

Changing the value in sessionStorage does not trigger the onChange event (Next.js)

When I use a custom hook to load data from session storage into an input field, I noticed that the onChange() function doesn't trigger if I delete the entire content of the input. However, it works fine if I add or delete just one character. This issu ...

Obtaining IDs of Divs that have been Dragged into a Drop Zone upon Clicking a Button using JavaScript

I'm currently working on a solution to extract the ids of dragged divs once they have been placed in the drop zone. Each drag component is assigned an id ranging from drag1 through drag8, while the drop zone is labeled as div drop zone. Since there a ...