How to add active className in nextjs

Viewed 4859

I am new to Nextjs. I have to have an active className when a nav-link is selected. I am using Nextjs+react-bootstrap in my project. The feature I want to implement is when someone clicks on a specific link it's colour should be changed

my Navbar component looks like this -

import React from "react";
import { Navbar, Nav, Button } from "react-bootstrap";
import Link from "next/link";
import "../../styles/Header.module.css";

const Header = () => {
  return (
    <div className="header">
      <Navbar expand="lg">
        <Link href="/">
          <Navbar.Brand style={{ padding: "8px 50px" }}>
            <img
              src="/logo.svg"
              left="60px"
              top="25px"
              width="112px"
              height="23px"
              className="d-inline-block align-top"
              alt="Openhouse logo"
            />
          </Navbar.Brand>
        </Link>
        <Navbar.Toggle aria-controls="basic-navbar-nav" />
        <Navbar.Collapse id="basic-navbar-nav" className="justify-content-end">
          <Nav className="ml-auto">
            <Link href="/classes" passHref>
              <Nav.Link style={{ padding: "8px 50px" }}>Classes</Nav.Link>
            </Link>
            <Link href="/clubs" passHref>
              <Nav.Link style={{ padding: "8px 50px" }}>Clubs</Nav.Link>
            </Link>
            <Link href="/aboutUs" passHref>
              <Nav.Link style={{ padding: "8px 50px" }}>AboutUs</Nav.Link>
            </Link>
          </Nav>
          <Button variant="warning" size="sm">
            Chat with us
          </Button>
        </Navbar.Collapse>
      </Navbar>
    </div>
  );
};

export default Header;

1 Answers

This special version of the Link tag is called NavLink and adds styling attributes to the rendered element when it matches the current URL

The class is given to the element when it is active by writing:

<NavLink to="/about" activeClassName="active">
  About
</NavLink>'
Related