How to Use Link Component in React Router
In this article, you will learn how to implement the
Link component in a React application using React Router.
We will cover why the Link component is essential for
client-side routing, how to install the necessary library, and provide a
step-by-step guide with clear code examples to integrate it into your
project.
Why Use the Link Component?
In standard HTML, the <a> (anchor) tag is used for
navigation. However, in a Single Page Application (SPA) built with
React, using a standard anchor tag forces the browser to reload the
entire page.
The Link component from React Router solves this by
intercepting the browser’s default navigation behavior. It updates the
URL in the address bar and updates the UI without triggering a full page
refresh, resulting in a faster and smoother user experience.
Step 1: Install React Router DOM
To use the Link component, you must first install the
react-router-dom package in your React project. Run the
following command in your terminal:
npm install react-router-domStep 2: Set Up the BrowserRouter
Before using the Link component, you need to wrap your
application component tree with BrowserRouter. This enables
routing capabilities throughout your application.
Open your entry file (typically index.js or
main.jsx) and configure it as follows:
import React from 'react';
import ReactDOM from 'react-dom/client';
import { BrowserRouter } from 'react-router-dom';
import App from './App';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<BrowserRouter>
<App />
</BrowserRouter>
</React.StrictMode>
);Step 3: Implement the Link Component
Once the router is set up, you can import and use the
Link component in your components. The Link
component requires a to prop, which specifies the
destination path.
Here is an example of a navigation bar component using
Link:
import React from 'react';
import { Link } from 'react-router-dom';
function Navigation() {
return (
<nav>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/about">About</Link>
</li>
<li>
<Link to="/contact">Contact</Link>
</li>
</ul>
</nav>
);
}
export default Navigation;Passing State via Link
You can also pass custom data to the destination route. To do this,
use the state prop on the Link component:
<Link to="/profile" state={{ fromDashboard: true }}>
View Profile
</Link>In the destination component, you can retrieve this state by using
the useLocation hook from
react-router-dom:
import { useLocation } from 'react-router-dom';
function Profile() {
const location = useLocation();
const { fromDashboard } = location.state || {};
return (
<div>
<h1>Profile Page</h1>
{fromDashboard && <p>Welcome back from the dashboard!</p>}
</div>
);
}