skip to Main Content

i have a reactJs project. the navlink isActive is true when i click on the item. i have two navlinks Users and Attorneys. if user click on Users then Users is active. onn that page we have a list of users whenn i click on user 1 its open a new tab where. where the users NavItem is not active.

what i have tried is this

// Component with NavLink and localStorage handling
import React, { useEffect, useState } from 'react';
import { NavLink } from 'react-router-dom';

const Navigation = () => {
  const [activeNavLink, setActiveNavLink] = useState(null); // State to manage active NavLink

  // Function to handle NavLink click
  const handleNavLinkClick = (navLinkKey) => {
    // Store the active state in localStorage
    localStorage.setItem('activeNavLink', navLinkKey);
    setActiveNavLink(navLinkKey); // Update active state in component state
  };

  useEffect(() => {
    // Retrieve active state from localStorage on component mount
    const storedActiveNavLink = localStorage.getItem('activeNavLink');
    setActiveNavLink(storedActiveNavLink); // Set active state in component state
  }, []);

  return (
    <div>
      <NavLink
        to="/home"
        onClick={() => handleNavLinkClick('/home')}
        className={activeNavLink === '/home' ? 'active' : ''}
      >
        Home
      </NavLink>
      <NavLink
        to="/about"
        onClick={() => handleNavLinkClick('/about')}
        className={activeNavLink === '/about' ? 'active' : ''}
      >
        About
      </NavLink>
      {/* Add more NavLinks as needed */}
    </div>
  );
};

export default Navigation;

4

Answers


  1. Instead of using state to check whether it is active or not use pathname. For example:

       <NavLink
        to="/home"
        onClick={() => handleNavLinkClick('/home')}
        className={window.location.pathanme === '/home' ? 'active' : ''}
      >
        Home
      </NavLink>
    

    State refreshes when you reload the page or go in a new tab.

    Login or Signup to reply.
  2. When you use NavLink states is changing so just use ‘preventDefault’.

      <NavLink
        to="/home"
        onClick={(e) => {
          e.preventDefault()
          handleNavLinkClick('/home')
        }}
        className={activeNavLink === '/home' ? 'active' : ''}
      >
        Home
    </NavLink>
    Login or Signup to reply.
  3. I think you can solve this easier:

      const location = useLocation();
    
    
      <NavLink
        to="/home"
        className={location.pathname.includes("home") ? 'active' : ''}
      >
        Home
      </NavLink>
    
    Login or Signup to reply.
  4. import { NavLink, useLocation } from 'react-router-dom';
    
    const navItems = [
        { to: '/', label: 'Home' },
        { to: '/users', label: 'Users' },
        { to: '/posts', label: 'Posts' },
        { to: '/albums', label: 'Albums' },
    ];
    
    const Nav = () => {
        const location = useLocation();
    
        return (
            <div>
                {navItems.map((item) => (
                    <NavLink
                        key={item.label}
                        to={item.to}
                        className={location.pathname === item.to ? 'active' : ''}
                    >
                        {item.label}
                    </NavLink>
                ))}
            </div>
        );
    };
    
    export default Nav;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search