Highlight current nav link in react
Highlight current nav link in React
Highlighting the current navigation link is a common requirement in web applications, especially in single-page applications built with React. When a user clicks on a link, you want to indicate which page they are currently on by highlighting the corresponding navigation link. In this post, we'll explore a few ways to achieve this using React.
Method 1: Using state
One way to highlight the current navigation link is to use state in your React component. When the user clicks on a link, you update the state to indicate which link is active, and then use that state to apply a CSS class to the corresponding navigation item.
import React, { useState } from 'react';
const Navigation = () => {
const [activeLink, setActiveLink] = useState('home');
const handleLinkClick = (link) => {
setActiveLink(link);
};
return (
<nav>
<ul>
<li className={activeLink === 'home' ? 'active' : ''}>
<a href="#" onClick={() => handleLinkClick('home')}>Home</a>
</li>
<li className={activeLink === 'about' ? 'active' : ''}>
<a href="#" onClick={() => handleLinkClick('about')}>About</a>
</li>
<li className={activeLink === 'contact' ? 'active' : ''}>
<a href="#" onClick={() => handleLinkClick('contact')}>Contact</a>
</li>
</ul>
</nav>
);
};
In the code above, we use the useState
hook to create a state variable called activeLink
. We also define a handleLinkClick
function that updates the active link when a link is clicked. Finally, we apply the active
class to the navigation item if the active link matches the link being rendered.
Method 2: Using React Router
If you're using React Router for your navigation, you can use its built-in functionality to highlight the active link. React Router provides a NavLink
component that automatically applies a CSS class to the active link.
import { NavLink } from 'react-router-dom';
const Navigation = () => {
return (
<nav>
<ul>
<li>
<NavLink exact to="/" activeClassName="active">Home</NavLink>
</li>
<li>
<NavLink to="/about" activeClassName="active">About</NavLink>
</li>
<li>
<NavLink to="/contact" activeClassName="active">Contact</NavLink>
</li>
</ul>
</nav>
);
};
In the code above, we use the NavLink
component from React Router, which automatically applies an activeClassName
to the active link. We also use the exact
prop on the home link to ensure that it only matches the exact route.
Conclusion
There are multiple ways to highlight the current navigation link in React, depending on your requirements and setup. The first method uses state to manually update the active link, while the second method uses React Router's built-in NavLink
component to automatically highlight the active link. Choose the method that works best for your application and enjoy a more intuitive user experience!