React Router DOM is a popular library for handling routing in React applications. It enables navigation between different components without requiring full page reloads. It provides various features like:
Dynamic routing (routes defined as components)
Nested routes (child routes within parent routes)
Route parameters (dynamic paths like
/user/:id
)Programmatic navigation (navigate via code)
Install react-router-dom
npm i react-router-dom
Create router (App.jsx)
import {createBrowserRouter, RouterProvider} from 'react-router-dom'
import Home from './screens/Home.jsx'
import Login from './screens/Login.jsx'
import Register from './screens/Register.jsx'
const router = createBrowserRouter([
{
path: '/',
element: <Home/>,
},
{
path: '/login',
element: <Login/>,
},
{
path: '/register',
element: <Register/>
},
])
function App() {
return (
<div>
<RouterProvider router={router}/>
</div>
);
}
export default App;
Now routers are provides to website. you can hit url with this routes to access respective page. Now we will create a Navigation bar and provide UI for navigating to pages.
Navigation Bar
If we use Anchor tag to provide routes, the whole page will refreshed. hence we avoid using Anchor tag in react application.
Instead we use Link or NavLink to provide links
import React from "react";
import "./Components.css";
import Home from "../screens/Home.jsx";
import Login from "../screens/Login.jsx";
import Register from "../screens/Register.jsx";
import { Link } from "react-router-dom";
const Navbar = () => {
return (
<div className="Navbar">
<ul>
<li>
<Link to="/"> Home </Link>
</li>
<li>
<Link to="/login">Login</Link>
</li>
<li>
<Link to="/register">Register</Link>
</li>
</ul>
</div>
);
};
export default Navbar;
You can update Home router as
{
path: "/",
element: <div>
<Navbar/>
<Home />
</div>,
},
NavLink
<NavLink>
is a special type of <Link>
in React Router that allows you to apply styles dynamically based on the active route.
import { NavLink } from "react-router-dom";
const Navbar = () => {
return (
<nav>
<NavLink to="/" className={({ isActive }) => (isActive ? "active" : "")}>
Home
</NavLink>
<NavLink to="/about" className={({ isActive }) => (isActive ? "active" : "")}>
About
</NavLink>
</nav>
);
};
export default Navbar;
Parameters
in App.jsx add one more route with parameter
{
path: "/userProfile/:userId",
element: (
<div>
<Navbar />
<Profile />
</div>
),
},
Access parameter in <Profile/>
import React from 'react'
import { useParams } from 'react-router-dom'
const Profile = () => {
const {id} = useParams();
return (
<div>
User Profile of userId = {id}
</div>
)
}
export default Profile
useNavigate
useNavigate
is a React Router hook that allows you to navigate between pages programmatically without using <Link>
or <NavLink>
.
First, import useNavigate
from react-router-dom
and use it inside your component:
import { useNavigate } from "react-router-dom";
const Home = () => {
const navigate = useNavigate(); // Hook to navigate
return (
<div>
<h1>Home Page</h1>
<button onClick={() => navigate("/about")}>Go to About</button>
</div>
);
};
export default Home;
๐ When you click the button, it navigates to /about
without reloading the page.
Nested Routing
What is Nested Routing?
Nested routing allows you to define child routes inside a parent route, making it easier to structure complex applications.
For example:
/dashboard
โ Parent route/dashboard/profile
โ Nested route/dashboard/settings
โ Nested route
{
path: "/dashboard",
element: <Dashboard />,
children: [
{ path: "profile", element: <Profile /> },
{ path: "settings", element: <Settings /> },
],
},
What is <Outlet>?
<Outlet>
is a placeholder component that tells React Router where to render child components inside a parent layout.
import { Outlet, Link } from "react-router-dom";
const Dashboard = () => {
return (
<div>
<h1>Dashboard</h1>
<nav>
<Link to="profile">Profile</Link> | <Link to="settings">Settings</Link>
</nav>
<hr />
{/* This is where child routes will render */}
<Outlet />
</div>
);
};
export default Dashboard;
How It Works?
Visiting
/dashboard
only shows the Dashboard page.Clicking Profile (
/dashboard/profile
) or Settings (/dashboard/settings
) updates only the<Outlet>
section.The
<Outlet>
component insideDashboard.jsx
renders the respective child component dynamically.
Handling Page Not Found
If a user tries to access an undefined route, you can show a 404 Not Found page using the path: "*"
.
add below route at last after all routes
// Default route for unknown pages
{
path: "*",
element: <NotFound />,
},
NotFound.jsx
const NotFound = () => {
return (
<div>
<h1>404 - Page Not Found</h1>
<p>Oops! The page you are looking for does not exist.</p>
</div>
);
};
export default NotFound;