Introduction to React Router
React Router is a routing library used in React applications to display different components based on the current URL. It helps developers build multi-page experiences within a Single Page Application (SPA) without requiring a complete browser page reload for every navigation.
For example, an e-commerce application can use React Router to display Home, Products, Product Details, About, Contact, and Login pages using different URLs.
React JS Training: Explore JustAcademy React JS Training
Course Demo: Register for React JS Course Demo
1. What Is React Router?
React Router connects browser URLs with React components. When a user visits a particular route, React Router matches the URL against the application's route configuration and renders the appropriate component.
For example:
/ displays the Home page.
/about displays the About page.
/contact displays the Contact page.
/products displays the Products page.
/login displays the Login page.
React Router also supports nested routes, dynamic URL parameters, navigation links, programmatic navigation, and more advanced data-loading features.
2. Why Do We Need React Router?
React is a UI library for building interfaces. When an application contains multiple views, React Router provides a structured way to associate URLs with those views.
Benefits of React Router
- Client-side navigation: Move between views without a full page reload during normal client-side navigation.
- URL-based rendering: Display the correct component for a particular URL.
- Browser history: Support Back and Forward navigation.
- Dynamic routes: Create routes containing values such as product IDs or user IDs.
- Nested routing: Render child pages inside shared layouts.
- Navigation links: Use components such as
Link and NavLink.
- Programmatic navigation: Navigate after actions such as successful form submission.
- Organized applications: Separate pages and route definitions into manageable components.
3. What Is Routing?
Routing is the process of determining which content or component should be displayed based on the current URL or navigation request.
In a React application, routing commonly maps a URL path to a React component.
Example of route mapping
| URL Path |
Component |
Purpose |
/ |
Home |
Displays the home page. |
/about |
About |
Displays information about the application. |
/services |
Services |
Displays available services. |
/contact |
Contact |
Displays contact information. |
/products/101 |
ProductDetails |
Displays details for a specific product. |
4. Installing React Router
For a new application using the current declarative React Router API, install the react-router package.
Installation command
npm install react-router
If you already have a React project, run this command from the project's root directory.
Note: Existing projects using React Router v6 or older tutorials may use imports from react-router-dom. Follow the import conventions for the installed version rather than mixing examples from different versions.
5. Important React Router Components
React Router provides components and Hooks for defining routes and navigating between them.
| Component or Hook |
Purpose |
BrowserRouter |
Provides browser-based routing using the History API. |
Routes |
Finds the best matching route for the current location. |
Route |
Associates a path with a component to render. |
Link |
Creates a navigation link without a full page reload during normal client-side navigation. |
NavLink |
Creates a navigation link that can identify the active route. |
Outlet |
Renders a matching child route inside a parent layout. |
useNavigate() |
Provides a function for programmatic navigation. |
useParams() |
Reads dynamic parameters from the matched URL. |
useLocation() |
Provides information about the current location. |
6. Understanding BrowserRouter
BrowserRouter is a router component that uses the browser History API to keep the interface synchronized with the current URL.
It allows the application to respond to navigation changes and render the appropriate routes.
Example
import { BrowserRouter } from "react-router";
function App() {
return (
<BrowserRouter>
<h1>My React Application</h1>
</BrowserRouter>
);
}
export default App;
In this example, the application is wrapped in BrowserRouter. In a complete application, route definitions are normally placed inside this router.
7. Understanding Routes and Route
The Routes component contains route definitions. Each Route specifies a URL pattern and the component that should render when that pattern matches.
Example
import {
BrowserRouter,
Routes,
Route
} from "react-router";
function Home() {
return <h2>Home Page</h2>;
}
function About() {
return <h2>About Page</h2>;
}
function Contact() {
return <h2>Contact Page</h2>;
}
function App() {
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/contact" element={<Contact />} />
</Routes>
</BrowserRouter>
);
}
export default App;
Explanation:
BrowserRouter enables browser-based routing.
Routes groups the route definitions.
Route defines a URL path.
element specifies the React component to render.
- React Router selects the best matching route for the current URL.
8. Creating Separate Page Components
In a larger application, keeping each page in a separate component file improves code organization and maintainability.
Home.jsx
function Home() {
return (
<div>
<h1>Home Page</h1>
<p>Welcome to our website.</p>
</div>
);
}
export default Home;
About.jsx
function About() {
return (
<div>
<h1>About Us</h1>
<p>Learn more about our company.</p>
</div>
);
}
export default About;
App.jsx
import {
BrowserRouter,
Routes,
Route
} from "react-router";
import Home from "./Home";
import About from "./About";
function App() {
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
</BrowserRouter>
);
}
export default App;
When the user visits /, React Router renders the Home component. When the user visits /about, it renders the About component.
9. Navigating with Link
The Link component provides client-side navigation between routes. It renders a link that users can click to move to another view.
Example
import {
BrowserRouter,
Routes,
Route,
Link
} from "react-router";
function Home() {
return <h2>Welcome Home</h2>;
}
function About() {
return <h2>About Our Website</h2>;
}
function App() {
return (
<BrowserRouter>
<nav>
<Link to="/">Home</Link>
{" | "}
<Link to="/about">About</Link>
</nav>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
</BrowserRouter>
);
}
export default App;
Key points:
to="/" navigates to the Home route.
to="/about" navigates to the About route.
Link supports normal browser link behaviour, including opening links in a new tab.
- Use
Link instead of a plain anchor for normal navigation within a React Router application.
10. Understanding NavLink
NavLink works similarly to Link, but it also provides an active state when its route matches the current URL. This is useful for navigation bars and side menus.
Example
import { NavLink } from "react-router";
function Navigation() {
return (
<nav>
<NavLink
to="/"
end
className={({ isActive }) =>
isActive ? "active" : ""
}
>
Home
</NavLink>
{" | "}
<NavLink to="/about">About</NavLink>
</nav>
);
}
export default Navigation;
The isActive value can be used to apply styling to the currently active navigation item. The end prop on the Home link ensures that it matches the root path rather than remaining active for every path beginning with that route.
11. Dynamic Routes and URL Parameters
Dynamic routes contain variable segments. They are useful when the same component must display different information for different users, products, or records.
Example route
<Route path="/products/:productId" element={<ProductDetails />} />
The :productId segment represents a dynamic parameter. For example, /products/101 matches the route with productId set to 101.
Reading parameters with useParams()
import { useParams } from "react-router";
function ProductDetails() {
const { productId } = useParams();
return (
<div>
<h2>Product Details</h2>
<p>Product ID: {productId}</p>
</div>
);
}
export default ProductDetails;
The useParams() Hook returns the dynamic parameters for the matched route. Parameters are strings, so convert them when your application requires a number.
12. Programmatic Navigation with useNavigate()
The useNavigate() Hook lets a component navigate to another route through a function. It is useful when navigation should happen after an action, such as a successful form submission.
Example
import { useNavigate } from "react-router";
function Login() {
const navigate = useNavigate();
function handleLogin() {
// Perform authentication before navigating.
navigate("/dashboard");
}
return (
<button onClick={handleLogin}>
Login
</button>
);
}
export default Login;
This simplified example navigates when the button is clicked. In a real application, perform and validate the authentication process before navigating to a protected page.
Important: Prefer Link or NavLink for ordinary user navigation. Use useNavigate() when navigation needs to happen programmatically.
13. Understanding Nested Routes
Nested routes allow child pages to render inside a parent layout. They are useful when several pages share a header, sidebar, dashboard menu, or footer.
Example
import {
BrowserRouter,
Routes,
Route,
Outlet
} from "react-router";
function DashboardLayout() {
return (
<div>
<h1>Dashboard</h1>
<Outlet />
</div>
);
}
function Overview() {
return <p>Dashboard Overview</p>;
}
function Settings() {
return <p>Dashboard Settings</p>;
}
function App() {
return (
<BrowserRouter>
<Routes>
<Route path="/dashboard" element={<DashboardLayout />}>
<Route index element={<Overview />} />
<Route path="settings" element={<Settings />} />
</Route>
</Routes>
</BrowserRouter>
);
}
export default App;
Explanation:
- The parent route uses the path
/dashboard.
Outlet indicates where the matching child route should appear.
- The index route renders the Overview component at
/dashboard.
- The Settings component renders at
/dashboard/settings.
14. Handling Unknown Routes
A user may enter a URL that does not match any route. You can create a fallback route using the wildcard path *.
import { Routes, Route } from "react-router";
function NotFound() {
return <h2>404 - Page Not Found</h2>;
}
function AppRoutes() {
return (
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="*" element={<NotFound />} />
</Routes>
);
}
The wildcard route provides a user-friendly fallback for unmatched URLs. Ensure that the components used in the example, such as Home and About, are defined or imported.
15. React Router and Single Page Applications
A Single Page Application loads its main HTML document and updates the interface as users interact with the application. React Router supports this pattern by matching URLs and rendering the corresponding React components during client-side navigation.
Traditional page navigation vs. React Router
| Feature |
Traditional full page navigation |
React Router navigation |
| Navigation |
Usually requests a new document from the server. |
Normally updates the URL and renders the matching React route on the client. |
| Page reload |
Typically reloads the document. |
Typically avoids a full document reload for internal navigation. |
| UI updates |
New document and page content are loaded. |
The matched React components are rendered or updated. |
| Browser history |
Managed by the browser. |
Integrated with the browser's history through the router. |
Important: Directly opening or refreshing a nested route requires appropriate server configuration so the application can serve its entry document for supported client-side paths. Otherwise, the server may return a 404 before React Router loads.
16. Common React Router Mistakes
| Mistake |
Problem |
Solution |
| Forgetting BrowserRouter |
Router components may not have routing context. |
Wrap the application with the appropriate router provider. |
| Using an incorrect import path |
Imports may not match the installed React Router version. |
Follow the documentation for your installed version. |
| Using a plain anchor for every internal link |
It may trigger a full page navigation. |
Use Link for ordinary internal navigation. |
| Incorrect route path |
The expected component may not render. |
Verify the path and current URL. |
| Forgetting Outlet |
Nested child routes have no place to render in the parent layout. |
Place Outlet where child content should appear. |
| Reading a parameter without a matching route |
The expected parameter may be missing. |
Define the dynamic segment and access it with useParams(). |
| Using useNavigate outside router context |
The Hook cannot access the router. |
Use it in a component rendered within the router. |
| Refreshing a nested URL returns 404 |
The server may not be configured for client-side routes. |
Configure the server to serve the application entry document for appropriate routes. |
17. Best Practices for React Router
- Use descriptive and consistent URL paths.
- Keep page components separate when the application grows.
- Use
Link and NavLink for internal navigation.
- Use
useNavigate() for navigation triggered by application logic.
- Use dynamic route parameters for resource-specific pages.
- Use nested routes to share layouts across related pages.
- Provide a not-found route for invalid URLs.
- Check route behaviour with browser Back and Forward navigation.
- Configure production hosting for direct route access and refreshes.
- Keep the React Router version and import conventions consistent throughout the project.
18. Practical Project: Simple Multi-Page Website
Objective: Build a basic React website with Home, About, Services, and Contact pages.
Step 1: Install React Router
npm install react-router
Step 2: Create page components
function Home() {
return <h2>Home Page</h2>;
}
function About() {
return <h2>About Page</h2>;
}
function Services() {
return <h2>Services Page</h2>;
}
function Contact() {
return <h2>Contact Page</h2>;
}
Step 3: Configure routes and navigation
import {
BrowserRouter,
Routes,
Route,
Link
} from "react-router";
function Home() {
return <h2>Home Page</h2>;
}
function About() {
return <h2>About Page</h2>;
}
function Services() {
return <h2>Services Page</h2>;
}
function Contact() {
return <h2>Contact Page</h2>;
}
function App() {
return (
<BrowserRouter>
<nav>
<Link to="/">Home</Link> | {" "}
<Link to="/about">About</Link> | {" "}
<Link to="/services">Services</Link> | {" "}
<Link to="/contact">Contact</Link>
</nav>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/services" element={<Services />} />
<Route path="/contact" element={<Contact />} />
<Route path="*" element={<h2>404 - Page Not Found</h2>} />
</Routes>
</BrowserRouter>
);
}
export default App;
Expected result: The navigation links allow users to move between the four pages. Each URL renders its matching component, and unknown paths display the not-found message.
19. Frequently Asked Interview Questions
Q1. What is React Router?
React Router is a routing library that maps URLs to React components and supports navigation within React applications.
Q2. Why is React Router used?
It allows an application to display different views based on the URL and supports client-side navigation and browser history.
Q3. What is BrowserRouter?
It is a router that uses the browser History API to synchronize the URL with the React interface.
Q4. What is the difference between Routes and Route?
Routes groups route definitions and selects a matching route, while Route defines a path and the component to render.
Q5. What is the difference between Link and NavLink?
Link provides navigation, while NavLink additionally exposes an active state for styling the current navigation item.
Q6. What are dynamic routes?
Dynamic routes contain variable path segments, such as /products/:productId, that can represent different resources.
Q7. What is useParams()?
It is a Hook that reads the dynamic parameters from the current matched route.
Q8. What is useNavigate()?
It is a Hook that provides a function for navigating programmatically to another route.
Q9. What are nested routes?
Nested routes allow child pages to render within a parent route layout, commonly using Outlet.
Q10. What is a 404 route?
It is a fallback route that displays a not-found page when the URL does not match the application's defined routes.
20. Revision Checklist
- Understand the purpose of React Router.
- Install the correct React Router package.
- Understand
BrowserRouter, Routes, and Route.
- Create separate page components.
- Navigate using
Link and NavLink.
- Understand dynamic routes and
useParams().
- Use
useNavigate() when programmatic navigation is needed.
- Understand nested routes and
Outlet.
- Create a fallback not-found route.
- Test browser history and direct URL access.
21. Conclusion
React Router is an essential tool for creating multi-view React applications. It connects URLs with components and provides navigation, dynamic parameters, nested layouts, and programmatic routing. By understanding its core components and Hooks, developers can build applications that are easier to navigate, maintain, and extend.
Continue learning: JustAcademy React JS Training | Register for React JS Course Demo
22. Official Reference
Read the official documentation for more information: React Router Installation, React Router Routing, and React Router Navigation.