Web TippsUse custom web fonts in Google Sheets charts(08.09.2026 um 17:05 Uhr)
Web TippsIntroducing the new 1Password App for Google Chat(08.09.2026 um 18:02 Uhr)
Web TippsUse custom web fonts in Google Sheets charts(08.09.2026 um 17:05 Uhr)
Web TippsIntroducing the new 1Password App for Google Chat(08.09.2026 um 18:02 Uhr)

🔧 Programmierung 🕛 vor 1 Jahr 6 Min Lesezeit
0

Advanced Concepts and Practical Guide (Part 3)

↗ Quelle (dev.to)
🗣️ Stimme:
📑 Inhaltsübersicht

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




  1. Import useNavigate from react-router-dom.

  2. Call useNavigate() to get the navigation function.

  3. Use this function to navigate to a new route programmatically.









Example: Redirecting After Login






CODE
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>




  1. Import Navigate from react-router-dom.

  2. Use it inside your component to redirect users to another route.









Example: Redirecting from a NotFound Page






CODE
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: When true, 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






CODE
import { Navigate, Outlet } from "react-router-dom";

function ProtectedRoute({ isAuthenticated }) {
return isAuthenticated ? <Outlet /> : <Navigate to="/login" />;
}

export default ProtectedRoute;












Complete Example






CODE
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




  1. Import useLocation from react-router-dom.

  2. Call useLocation() to get the location object.









Example: Displaying the Current Path






CODE
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






CODE
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






CODE
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






CODE
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






CODE
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:




  1. Programmatic Navigation with useNavigate

  2. Redirection with <Navigate>

  3. Protected Routes

  4. Using useLocation for URL Information

  5. Handling 404 Pages

  6. Query Parameters with useSearchParams

  7. 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! 🚀

Vollständiger Original-Bericht
Ausführliche Details, Code-Beispiele & Hersteller-Stellungnahme auf dev.to.
↗ Original-Artikel auf dev.to lesen
Wie bewertest du diesen Beitrag?
1 Klick Feedback
Teilen mit Netzwerk & Team:

Community-Analysen & Experten-Meinungen 0

Verfasse deine eigene Analyse, teile Workarounds oder diskutiere diesen Vorfall im Blog.
Noch keine Community-Analyse verfasst. Markiere einen Textabschnitt oder klicke oben auf Eigene Analyse verfassen“!
Community Pulse: Relevanz-Einschätzung
1 Klick Experten-Votum
🔴 Akute Relevanz 0%
🟡 In Evaluierung 0%
🟢 Keine Auswirkung 0%
Spannende Innovation 0%
Verwandte Story-Cluster & Quellen (Vektor-KI)
Port 8095 Engine
3 Quellen
Use custom web fonts in Google Sheets charts
2 Quellen
Introducing the new 1Password App for Google Chat
1 Quelle
Context-aware access controls are available for Gemini Enterprise in the Admin console
Ähnliche Beiträge
🔍 Verwandte News

Auch interessante Nachrichten Advanced Concepts and Practical Guide (Part 3)

Thematisch verwandte Begriffe: Advanced, Concepts, Practical, Guide · 6 Treffer

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...