React Router is a popular library that provides routing and navigation capabilities to React applications. Many modern websites are actually made up of a single page, but they look like multiple pages because they contain components that render like separate pages. These are usually referred to as SPAs – single-page applications.
To use React Router, you first have to install it using NPM:
npm install react-router-dom
Some of the main components in react-router-dom are:
BrowserRouter
To use BrowserRouter
, you first need to wrap your application with it, usually in your top-level App
component. Once you’ve wrapped your application with BrowserRouter
, you can use other components and APIs provided by react-router-dom
, such as <Route>
, <Link>
, and <Routes>
, to define the routes for your application and provide a way to navigate between them.
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import App from './App';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<BrowserRouter>
<App />
</BrowserRouter>
);
Route
Route
is a component provided by the react-router-dom
package that enables you to define a route for your React application. It takes two main props: path
and component
.
For example, say we wanted to render a About component whenever a user navigated to the /about path,
<Route path="/about" element={<About />}/>
Example:
import React from 'react';
import { Route } from 'react-router-dom';
import Home from './Home';
import About from './About';
const App = () => (
<div>
<Route exact path="/" element={<Home/>} />
<Route path="/about" element={<About/>} />
</div>
);
export default App;
Routes
Whenever you have one or more Route, you’ll most likely want to wrap them in a Routes
import React from 'react';
import { Routes, Route } from 'react-router-dom';
import Home from './Home';
import About from './About';
const App = () => (
<div>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
</div>
);
export default App;
Link
Link
is a component provided by the react-router-dom
package that enables client-side navigation between different views in a single-page application
import React from 'react';
import { Link } from 'react-router-dom';
const Navbar = () => (
<>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/about">About</Link></li>
<li><Link to="/contact">Contact</Link></li>
</ul>
</>
);
export default Navbar;
The Link
component provided by the react-router-dom
package is preferred over the standard HTML <a>
tag for client-side navigation in a React application for several reasons:
Link
prevents unnecessary page reloads: When using a standard<a>
tag, clicking the link will cause the browser to perform a full page reload, even if the destination URL is within the same application. WithLink
, clicking the link will only update the URL in the address bar and render the appropriate component based on the new URL, without requiring a full page reload.- The
Link
component can handle dynamic URLs that include URL parameters and query strings. It allows you to specify dynamic portions of the URL as parameters, and the router will automatically update the component’s props with the corresponding values from the URL. - The
Link
component integrates with React’s event system, which means you can attach event handlers to theLink
component just like you would with any other React component. This makes it easier to add custom behavior to your navigation links.
React-Router-Dom important concepts:
URL Parameters
URL parameters allow you to capture dynamic segments of a URL and use that information to render different components or views. URL parameters are defined using a colon (:) followed by a parameter name in the path prop of a Route component
<Route path="/users/:id" element={<UserDetails/>} />
You can also define multiple URL parameters in a Route component by separating them with slashes:
<Route path="/users/:id/posts/:postId" element={<PostDetails/>} />
useParams() Hook
useParams() hook is a utility provided by the react-router-dom library in React, which allows you to access URL parameters defined in a Route component.
Example:
<Route path="/users/:id" element={<UserDetails/>} />
import { useParams } from "react-router-dom";
function UserDetails() {
const parameters = useParams();
return (
<div>
<h2>User Detail {parameters.id}</h2>
</div>
);
}
import { useParams } from "react-router-dom";
function UserDetails() {
const { id } = useParams(); //destructuring method
return (
<div>
<h2>User Detail {id}</h2>
</div>
);
}
Nested Routes
Nested routes in React allow you to define child routes within a parent route, which can be useful for creating more complex and structured routing in your application
<Route path="/pricing" element={<Pricing />}>
<Route path="free" element={<FreePricing />} />
<Route path="premium" element={<PremiumPricing />} />
</Route>
import React from "react";
import { Outlet } from "react-router";
function Pricing() {
return (
<div>
Show Pricing
<Outlet />
</div>);
}
export default Pricing;
useNavigate() Hook
useNavigate() hook is a part of the react-router-dom library and is used for navigating programmatically between different routes in your application
import { useNavigate } from 'react-router-dom';
function MyComponent() {
const navigate = useNavigate();
const handleClick = () => {
navigate('/about');
};
return (
<div>
<h1>About Component</h1>
<button onClick={handleClick}>About</button>
</div>
);
}
Protected Routes
Private Routes in React Router (also called Protected Routes) require a user being authorized to visit a route. So if a user is not authorized for a specific page, they cannot access it
import React from "react";
import { Navigate, Outlet } from 'react-router';
function ProtectedRoutes() {
const navigate = useNavigate();
const isLoggedIn = false;
return (
<>
{isLoggedIn ? <Outlet/> : <Navigate to="/login" />}
</>
);
}
export default ProtectedRoutes;
Now, you can surround any Routes inside the ProtectedRoutes Component
<Route element={<ProtectedRoutes/>}>
<Route element={<Home/>}>
<Route path='/' element = {<Feed/>}/>
<Route path='/profile/:userId' element = {<Profile/>}/>
<Route path='/chat' element = {<Chat/>}/>
</Route>
</Route>
By using protected routes, you can ensure that only authenticated users can access certain parts of your application, and provide a better user experience by automatically redirecting users to the login page when necessary.
Check our other articles: https://satyam-arya.click/understanding-react-hooks/