3

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;
thelonelyCoder
  • 322
  • 4
  • 18
  • 2
    check this [thread](https://stackoverflow.com/questions/53262263/target-active-link-when-the-route-is-active-in-next-js) – sazzad Aug 17 '20 at 14:18

1 Answers1

-1

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>'
Salman
  • 59
  • 1
  • 3
  • 1
    to attribute is specific to react-router and for nextjs we use "href" –  Apr 05 '22 at 18:50