ArticleZip > Active Link With React Router

Active Link With React Router

Active Link With React Router

When working with React Router in your web development projects, ensuring that your navigation links appear active when users are on a specific page adds a valuable user experience. In this guide, we will walk you through how to implement active links with React Router, making it easier for users to identify the page they are currently viewing.

Firstly, we need to ensure that we have React Router set up in our project. If you haven't already installed React Router, you can do so by running the command `npm install react-router-dom`.

Once you have React Router installed, let's start by creating a basic navigation menu. We'll create a simple navigation bar component that contains a few links using the `Link` component from React Router.

Jsx

import React from 'react';
import { Link } from 'react-router-dom';

const Navbar = () => {
  return (
    <div>
      Home
      About
      Contact
    </div>
  );
};

export default Navbar;

Now that we have our basic navigation set up, we can focus on making the active links visually distinct. React Router provides a `NavLink` component that adds special styling to the active link.

Let's update our Navbar component to use the `NavLink` component instead of the regular `Link` component.

Jsx

import React from 'react';
import { NavLink } from 'react-router-dom';

const Navbar = () =&gt; {
  return (
    <div>
      Home
      About
      Contact
    </div>
  );
};

export default Navbar;

In the updated code snippet above, we replaced the `Link` component with `NavLink` and added the `activeClassName` prop, which specifies the class name to apply to the link when it is active. Here, we have used "active," but you can customize this class name to suit your project's styling.

Next, you'll need to add some CSS to style the active link based on the class name we provided in the `activeClassName` prop.

Css

.active {
  font-weight: bold;
  color: blue;
}

By adding this CSS snippet to your project, the active link will now appear with bold text and a blue color, making it stand out from the other navigation links.

And there you have it! You have successfully implemented active links with React Router in your project. Users will now be able to easily identify which page they are currently on, enhancing their overall navigation experience.

Feel free to customize the styling further to match the design of your web application and make the active links more visually appealing.

Incorporating active links with React Router is a simple yet effective way to improve user navigation and provide a more intuitive browsing experience. Happy coding!

×