Search code examples
javascriptcssreactjsreact-routerreact-router-dom

My Navlink active class having an issue in React-router-v6


I have created a navbar using React-Router v6. When we click on any li element the ".active" class will be applied. Now I styled the "active" class (like adding bg-color and colors) but when I click the home list item my logo also activated as I have provided the same path for logo image and home list item.

enter image description here

import React from "react";
import { NavLink } from "react-router-dom";
import "./Navbars.css";

function Navbars() {
  return (
    <div>
      <div>
        <ul className="navbar">
          <NavLink to="/">
            <img
              src="https://assets.ccbp.in/frontend/react-js/nxt-trendz-logo-img.png"
              alt="logo-image"
              className="logo-img"
            />
          </NavLink>
          <li>
            <NavLink to="/" className="navbar-link">
              Home
            </NavLink>
          </li>
          <li>
            <NavLink to="/carts" className="navbar-link">
              Carts
            </NavLink>
          </li>
          <li>
            <NavLink to="/products" className="navbar-link">
              Products
            </NavLink>
          </li>
          <li>
            <button type="button" className="btn btn-primary m-2">
              Logout
            </button>
          </li>
        </ul>
      </div>
    </div>
  );
}

export default Navbars;

Solution

  • The app is rendering two home "/" path links. If you don't want the image link to receive any "active" styling then I suggest rendering it as the regular Link component so the "active" class isn't applied.

    You will likely also want to render this link into a list item li element to keep the correct semantic HTML within the unordered list ul.

    import { Link, NavLink } from 'react-router-dom';
    
    ...
    
    <li>
      <Link to="/">
        <img
          src="https://assets.ccbp.in/frontend/react-js/nxt-trendz-logo-img.png"
          alt="logo-image"
          className="logo-img"
        />
      </Link>
    </li>
    <li>
      <NavLink to="/" className="navbar-link">
        Home
      </NavLink>
    </li>
    

    An alternative since all the "real" NavLink components your code renders also have a "navbar-link" classname, you can scope the "active" classname.

    Example:

    .navbar-link {
      ... normal NavLink rules
    }
    
    .navbar-link.active {
      ... active link rules
    }