REACT
React Router: Syntax, Usage, and Examples
React router is a library for handling navigation in React applications. It allows you to create single-page applications (SPAs) with multiple views without requiring full-page reloads. By managing URL changes and rendering components dynamically, it provides a seamless and efficient way to handle routing.
How to Use React Router
To use React Router, install it with npm or yarn:
npm install react-router-dom
Once installed, wrap your application in a BrowserRouter
component.
Setting Up Routes
import React from "react";
import { BrowserRouter as Router, Route, Routes } from "react-router-dom";
import Home from "./Home";
import About from "./About";
function App() {
return (
<Router>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
</Router>
);
}
export default App;
Each Route
maps a URL path to a component. The Routes
component acts as a container for defining routes.
When to Use React Router
Single-Page Applications
React Router is essential for SPAs where multiple views exist within a single HTML document. Instead of sending new requests to the server, React router updates the UI dynamically.
Dynamic Routes with Parameters
When handling user profiles, product pages, or any content with unique identifiers, dynamic routing lets you extract parameters from the URL.
import { useParams } from "react-router-dom";
function UserProfile() {
let { userId } = useParams();
return <h2>Profile of user {userId}</h2>;
}
Accessing /users/42
will set userId
to 42
.
Route Guards for Authentication
Protect sensitive pages by restricting access based on authentication status.
import { Navigate } from "react-router-dom";
function ProtectedRoute({ isAuthenticated, children }) {
return isAuthenticated ? children : <Navigate to="/login" />;
}
If the user isn’t authenticated, they are redirected to the login page.
Examples of React Router
Programmatic Navigation
Use the useNavigate
hook for navigation within components.
import { useNavigate } from "react-router-dom";
function Dashboard() {
const navigate = useNavigate();
return (
<div>
<h1>Dashboard</h1>
<button onClick={() => navigate("/")}>Go Home</button>
</div>
);
}
Clicking the button takes the user to the home page.
Redirecting Users
Redirects ensure users land on the correct page automatically.
import { Navigate } from "react-router-dom";
function OldPage() {
return <Navigate to="/new-page" />;
}
Anyone visiting /old-page
gets redirected to /new-page
.
Nested Routes
Organize content hierarchically by defining routes within routes.
import { Route, Routes } from "react-router-dom";
import Dashboard from "./Dashboard";
import Settings from "./Settings";
function App() {
return (
<Routes>
<Route path="/dashboard" element={<Dashboard />}>
<Route path="settings" element={<Settings />} />
</Route>
</Routes>
);
}
The URL /dashboard/settings
loads the Settings
component inside Dashboard
.
Learn More About React Router
Using Query Parameters
Extract and use query parameters to filter or customize content.
import { useLocation } from "react-router-dom";
function SearchResults() {
const { search } = useLocation();
const query = new URLSearchParams(search);
return <h2>Search term: {query.get("q")}</h2>;
}
Visiting /search?q=react
displays Search term: react
.
Managing Navigation History
Control the browser history to navigate between pages dynamically.
import { useNavigate } from "react-router-dom";
function Profile() {
const navigate = useNavigate();
return (
<div>
<button onClick={() => navigate(-1)}>Go Back</button>
<button onClick={() => navigate(1)}>Go Forward</button>
</div>
);
}
The navigate
function moves users forward or backward through history.
Route Guards for Role-Based Access
Restrict certain pages to specific user roles.
import { Navigate } from "react-router-dom";
function AdminRoute({ isAdmin, children }) {
return isAdmin ? children : <Navigate to="/unauthorized" />;
}
Users without admin rights get redirected to /unauthorized
.
Handling 404 Pages
Create a fallback for unrecognized routes.
function NotFound() {
return <h2>404 - Page Not Found</h2>;
}
function App() {
return (
<Routes>
<Route path="*" element={<NotFound />} />
</Routes>
);
}
Any invalid URL leads to the NotFound
component.
Using Layout Components
Keep navigation consistent across pages by using a shared layout.
import { Outlet } from "react-router-dom";
function Layout() {
return (
<div>
<nav>Navigation Bar</nav>
<main>
<Outlet />
</main>
</div>
);
}
function App() {
return (
<Routes>
<Route path="/" element={<Layout />}>
<Route index element={<Home />} />
<Route path="about" element={<About />} />
</Route>
</Routes>
);
}
The Outlet
component renders child routes inside the Layout
.
Using React Router with Server-Side Rendering
For server-side applications, StaticRouter
provides a way to handle routing.
import { StaticRouter } from "react-router-dom/server";
function App() {
return (
<StaticRouter location="/about">
<Routes>
<Route path="/about" element={<About />} />
</Routes>
</StaticRouter>
);
}
The location is passed manually to determine which component to render.
Integrating React Router with Modals
Instead of navigating to a separate page, modals can be displayed using routes.
import { useNavigate } from "react-router-dom";
function Modal() {
const navigate = useNavigate();
return (
<div className="modal">
<p>Modal Content</p>
<button onClick={() => navigate(-1)}>Close</button>
</div>
);
}
function App() {
return (
<Routes>
<Route path="/modal" element={<Modal />} />
</Routes>
);
}
Visiting /modal
opens the modal, and clicking "Close" takes the user back.
React Router with iframes
You can use React router to load content into an iframe dynamically.
function IframePage() {
return <iframe src="https://example.com" title="Embedded Page" />;
}
function App() {
return (
<Routes>
<Route path="/iframe" element={<IframePage />} />
</Routes>
);
}
This allows external content to be embedded while maintaining navigation.
React Router simplifies navigation and provides powerful tools to manage routes, dynamic content, and authentication. Whether handling nested routes, query parameters, or modals, it keeps navigation smooth and user-friendly.
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.