Advanced Concepts and Practical Guide of React Router(Part 3)
Harsh Mishra
Posted on November 13, 2024
In this final installment of the Ultimate Guide to React Router, we delve into the powerful features that make React Router a must-have library for building robust SPAs (Single Page Applications). We'll cover programmatic navigation, protected routes, URL management, 404 handling, and query parameters. Finally, we’ll provide a complete example that ties everything together.
1. Programmatic Navigation with useNavigate
What is Programmatic Navigation?
Programmatic navigation allows you to redirect users to specific routes based on actions (like a button click or form submission) or conditions (like user authentication). React Router's useNavigate
hook makes this process seamless.
How to Use useNavigate
- Import
useNavigate
fromreact-router-dom
. - Call
useNavigate()
to get the navigation function. - Use this function to navigate to a new route programmatically.
Example: Redirecting After Login
import { useNavigate } from "react-router-dom";
function Login() {
let navigate = useNavigate();
function handleLogin() {
// Simulate login logic
const loginSuccess = true;
if (loginSuccess) {
navigate("/dashboard"); // Redirect to dashboard
}
}
return <button onClick={handleLogin}>Login</button>;
}
export default Login;
- When the login logic succeeds, the user is redirected to the
/dashboard
route. - This eliminates the need for
<Link>
or<NavLink>
for conditional navigation.
2. Redirection with the Navigate
Component
The <Navigate>
component is used for automatic redirection. Unlike useNavigate
, which is invoked programmatically, <Navigate>
is used declaratively in your component tree.
How to Use <Navigate>
- Import
Navigate
fromreact-router-dom
. - Use it inside your component to redirect users to another route.
Example: Redirecting from a NotFound Page
import { Navigate } from "react-router-dom";
function NotFound() {
return <Navigate to="/" replace={true} />;
}
export default NotFound;
Key Features of <Navigate>
-
to
Prop: Specifies the target route. -
replace
Prop: Whentrue
, replaces the current history entry (prevents back navigation).
Use this for automatic redirects, such as in 404 pages or post-login flows.
3. Creating Protected Routes
What are Protected Routes?
Protected routes restrict access to certain parts of your app, requiring specific conditions to be met (e.g., user authentication). If the conditions are not met, the user is redirected to another route.
Implementing Protected Routes
React Router's <Outlet>
and <Navigate>
make it simple to create protected routes. Here's an example:
Example: Protected Route Component
import { Navigate, Outlet } from "react-router-dom";
function ProtectedRoute({ isAuthenticated }) {
return isAuthenticated ? <Outlet /> : <Navigate to="/login" />;
}
export default ProtectedRoute;
Complete Example
import { BrowserRouter, Routes, Route } from "react-router-dom";
import ProtectedRoute from "./ProtectedRoute";
import Dashboard from "./Dashboard";
import Login from "./Login";
function App() {
const isAuthenticated = false; // Simulate auth state
return (
<BrowserRouter>
<Routes>
{/* Protected Routes */}
<Route element={<ProtectedRoute isAuthenticated={isAuthenticated} />}>
<Route path="/dashboard" element={<Dashboard />} />
</Route>
{/* Public Routes */}
<Route path="/login" element={<Login />} />
</Routes>
</BrowserRouter>
);
}
export default App;
4. Using useLocation
for URL Details
What is useLocation
?
The useLocation
hook provides information about the current URL, including the pathname, search query, and hash.
How to Use useLocation
- Import
useLocation
fromreact-router-dom
. - Call
useLocation()
to get the location object.
Example: Displaying the Current Path
import { useLocation } from "react-router-dom";
function CurrentPage() {
let location = useLocation();
return <p>Current page: {location.pathname}</p>;
}
export default CurrentPage;
Location Object Structure
The location
object includes:
-
pathname
: The current path (e.g.,/dashboard
). -
search
: The query string (e.g.,?user=123
). -
hash
: The URL fragment (e.g.,#section
).
5. Handling 404 Pages
What is a 404 Page?
A 404 page is displayed when no routes match the user’s requested URL. You can use a catch-all route (*
) to handle these cases.
Example: Catch-All Route
import NotFound from "./NotFound";
function App() {
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="*" element={<NotFound />} /> {/* Catch-all */}
</Routes>
</BrowserRouter>
);
}
export default App;
6. Query Parameters with useSearchParams
What are Query Parameters?
Query parameters are key-value pairs appended to a URL, often used for filtering or searching. For example, /search?query=react
.
How to Use useSearchParams
React Router provides the useSearchParams
hook to manage query parameters.
Example: Reading Query Parameters
import { useSearchParams } from "react-router-dom";
function SearchPage() {
let [searchParams] = useSearchParams();
const query = searchParams.get("query");
return <h1>Search Results for: {query}</h1>;
}
export default SearchPage;
Example: Setting Query Parameters
function SetSearchParams() {
let [searchParams, setSearchParams] = useSearchParams();
function handleSearch() {
setSearchParams({ query: "react" });
}
return <button onClick={handleSearch}>Search for React</button>;
}
Complete Example with Nested, Protected, and Programmatic Navigation
import React from "react";
import {
BrowserRouter,
Routes,
Route,
Link,
useNavigate,
useParams,
Navigate,
Outlet,
useSearchParams,
useLocation,
} from "react-router-dom";
function Home() {
return <h1>Home Page</h1>;
}
function About() {
return <h1>About Page</h1>;
}
function Dashboard() {
return (
<div>
<h1>Dashboard</h1>
<Outlet />
</div>
);
}
function Profile() {
return <h1>Profile Page</h1>;
}
function Settings() {
return <h1>Settings Page</h1>;
}
function Login() {
let navigate = useNavigate();
function handleLogin() {
navigate("/dashboard");
}
return <button onClick={handleLogin}>Login</button>;
}
function ProtectedRoute({ isAuthenticated }) {
return isAuthenticated ? <Outlet /> : <Navigate to="/login" />;
}
function SearchPage() {
let [searchParams] = useSearchParams();
const query = searchParams.get("query");
return <h1>Search Results for: {query}</h1>;
}
function CurrentPage() {
let location = useLocation();
return <p>Current page: {location.pathname}</p>;
}
function NotFound() {
return <Navigate to="/" />;
}
function App() {
const isAuthenticated = true;
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/search" element={<SearchPage />} />
<Route element={<ProtectedRoute isAuthenticated={isAuthenticated} />}>
<Route path="/dashboard" element={<Dashboard />}>
<Route path="profile" element={<Profile />} />
<Route path="settings" element={<Settings />} />
</Route>
</Route>
<Route path="/login" element={<Login />} />
<Route path="*" element={<NotFound />} />
</Routes>
</BrowserRouter>
);
}
export default App;
Summary
This guide covered:
- Programmatic Navigation with
useNavigate
- Redirection with
<Navigate>
- Protected Routes
- Using
useLocation
for URL Information - Handling 404 Pages
- Query Parameters with
useSearchParams
- A Complete Example Combining All Concepts
By now, you should have a deep understanding of React Router and its advanced features. Whether you're building small SPAs or large-scale applications, these tools will help you create efficient and user-friendly navigation systems. Happy coding! 🚀
Posted on November 13, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.