Skip to main content

Link and NavLink Components in React Routing

In React Router, navigation is achieved using the Link and NavLink components. These components allow users to navigate between different routes without triggering a full page reload. In this tutorial, we'll explore how to use the Link and NavLink components with sample code and simple explanations.

The Link component is a simple way to navigate between routes. It renders an anchor tag (<a>) under the hood, but intercepts the click event to prevent a full page reload.

Here's an example of using the Link component for navigation:

JavaScript
// Navbar.js
import React from 'react';
import { Link } from 'react-router-dom';

function Navbar() {
return (
<nav>
<Link to="/">Home</Link>
<Link to="/about">About</Link>
<Link to="/contact">Contact</Link>
</nav>
);
}

export default Navbar;

In this example, the to prop of the Link component is used to specify the target route. When users click on a link, they will be navigated to the corresponding route.

The NavLink component is an extension of the Link component, with additional features for styling active routes. It adds an "active" class to the link when the current URL matches the target route.

Here's an example of using the NavLink component for navigation:

JavaScript
// Navbar.js
import React from 'react';
import { NavLink } from 'react-router-dom';

function Navbar() {
return (
<nav>
<NavLink exact to="/" activeClassName="active">
Home
</NavLink>
<NavLink to="/about" activeClassName="active">
About
</NavLink>
<NavLink to="/contact" activeClassName="active">
Contact
</NavLink>
</nav>
);
}

export default Navbar;

In this example, the activeClassName prop is used to specify the CSS class that will be applied to the active link. Additionally, the exact prop is used on the "Home" link to ensure that the active class is only applied when the URL exactly matches the target route.

Conclusion

In this tutorial, we have explored the Link and NavLink components in React Router. We've learned how to use these components for navigation and styling active routes. With this knowledge, you can create more user-friendly navigation systems in your React applications.

Remember to practice using these components in different routing scenarios to become more familiar with their features and capabilities. As you gain experience, you'll be able to create more complex and interactive navigation systems in your applications.