Welcome to our comprehensive guide on using Link and NavLink in React JS! This tutorial is designed to help beginners and intermediates alike understand these essential tools in the React ecosystem. Let's dive right in!
Before we start, let's understand why we need Link and NavLink. In a React application, we often have multiple pages or components that need to be navigated. Link and NavLink are React routing solutions that help us manage these navigations efficiently.
šÆ Key Point: Link is a built-in React component used for creating hyperlinks within a React application.
import React from 'react';
function LinkExample() {
return (
<div>
<a href="/about">About Us</a> š _Not recommended_
<Link to="/about">About Us</Link> ā
_Recommended_
</div>
);
}š” Pro Tip: Unlike the traditional HTML anchor tag, using <Link> ensures seamless navigation within your React application, as it handles things like preventing default behavior and updating the browser URL.
šÆ Key Point: NavLink is a more advanced routing solution in React, designed for creating navigation menus.
import React from 'react';
import { NavLink } from 'react-router-dom';
function NavLinkExample() {
return (
<div>
<NavLink to="/about">About Us</NavLink>
<NavLink to="/services">Services</NavLink>
<NavLink to="/contact">Contact Us</NavLink>
</div>
);
}š” Pro Tip: NavLink has an additional activeClassName prop that allows us to style the active (currently selected) link in our navigation menu.
šÆ Key Point: Understanding activeClassName and exact prop can help us improve the user experience of our navigation menus.
import React from 'react';
import { NavLink } from 'react-router-dom';
function NavLinkExample() {
return (
<div>
<NavLink activeClassName="active" to="/about">About Us</NavLink>
<NavLink exact activeClassName="active" to="/">Home</NavLink>
<NavLink activeClassName="active" to="/services">Services</NavLink>
<NavLink activeClassName="active" to="/contact">Contact Us</NavLink>
</div>
);
}š” Pro Tip: The exact prop ensures that the link is only considered active when the exact path matches. This helps avoid unnecessary active classes when partial matches occur.
You've now learned the basics of using Link and NavLink in a React application. These tools will help you create user-friendly, efficient navigation menus and hyperlinks within your projects.
What is the main difference between the traditional HTML anchor tag and React's Link component?
That's it for this lesson! In the next one, we'll delve deeper into React Router, exploring more advanced routing concepts like nested routes and protected routes. Until then, happy coding! š