Michael
Michael

Reputation: 155

activeClassName on Nav link not working - react

Trying to change the style of Nav link in the navbar when clicked , i understood from a google search that i should use "activeClassName". Tried using it and it's not working. What i'm doing wrong?

The menu code:

    <Navbar bg="none" expand="md">
      <Navbar.Brand href="/">Bloom</Navbar.Brand>
      <Navbar.Toggle aria-controls="basic-navbar-nav" />
      <Navbar.Collapse id="basic-navbar-nav">
        <Nav className="ml-auto order-0">
          <Nav.Link activeClassName="active" href="/contact">main</Nav.Link>
          <Nav.Link activeClassName="active" href="/about">main</Nav.Link>
          <Nav.Link activeClassName="active" href="/guide">main</Nav.Link>
          <Nav.Link activeClassName="active" href="/brands">main</Nav.Link>
          <Nav.Link activeClassName="active" href="/" exact>
            main
          </Nav.Link>
        </Nav>
      </Navbar.Collapse>
    </Navbar>

The styling:

   .active{
 color:red;
}

I try keeping my code simple as possible so if you have a better way would love to hear.

Upvotes: 2

Views: 838

Answers (1)

Gabriele Petrioli
Gabriele Petrioli

Reputation: 195992

You seem to be confusing it with the react router's NavLink element.

Your code seems to be using the react-bootstrap Nav.Link element.

You should use the activeKey prop on the parent Nav element to mark the active one.

<Nav className="ml-auto order-0" activeKey="/contact">
  <Nav.Link href="/contact">main</Nav.Link>
  <Nav.Link href="/about">main</Nav.Link>
  <Nav.Link href="/guide">main</Nav.Link>
  <Nav.Link href="/brands">main</Nav.Link>
  <Nav.Link href="/" exact>
    main
  </Nav.Link>
</Nav>

This will automatically add an active class to the active link.

Upvotes: 2

Related Questions