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
Instead of using state to check whether it is active or not use pathname. For example:
State refreshes when you reload the page or go in a new tab.
When you use NavLink states is changing so just use ‘preventDefault’.
I think you can solve this easier: