React Router for Navigation
React Router for Navigation
~13 Min. Lesezeit Zuletzt aktualisiert am August 8, 2026
SO FAR, only ONE page exists – react-router-dom (ALREADY installed in chapter 7) connects URLs to components, EXACTLY as in the earlier React courses.
Setting up the router
import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom';
import { useAuth } from './context/AuthContext';
import LoginPage from './pages/LoginPage';
import ProjectListPage from './pages/ProjectListPage';
function ProtectedRoute({ children }: { children: React.ReactNode }) {
const { token } = useAuth();
if (!token) {
return <Navigate to="/login" replace />;
}
return <>{children}</>;
}
function App() {
return (
<BrowserRouter>
<Routes>
<Route path="/login" element={<LoginPage />} />
<Route
path="/projects"
element={
<ProtectedRoute>
<ProjectListPage />
</ProtectedRoute>
}
/>
<Route path="/" element={<Navigate to="/projects" replace />} />
</Routes>
</BrowserRouter>
);
}
export default App;ProtectedRoute uses the SAME useAuth() hook from chapter 76 – NO token means an AUTOMATIC redirect to /login, EXACTLY like the 401 interceptor from chapter 77, but PROACTIVELY instead of REACTIVELY (BEFORE instead of AFTER a failed request).
Redirecting after login
// LoginPage.tsx - addition
import { useNavigate } from 'react-router-dom';
const navigate = useNavigate();
const loginMutation = useMutation({
// ...
onSuccess: (data) => {
login(data.token);
navigate('/projects');
},
});A detail page with a URL parameter
<Route path="/projects/:id" element={
<ProtectedRoute>
<ProjectDetailPage />
</ProtectedRoute>
} />// ProjectDetailPage.tsx
import { useParams } from 'react-router-dom';
function ProjectDetailPage() {
const { id } = useParams<{ id: string }>();
// EXACTLY like useProjects() from chapter 75, but for A SINGLE project
// ...
}:id in the route definition MATCHES the {id} placeholder from uriTemplate (chapters 13/39) on the backend side – the REST path structure NATURALLY carries over to the frontend routing structure.
Tipp: <Navigate replace /> instead of <Navigate /> prevents the login page from LANDING in the browser history – the back button THEN jumps to the page BEFORE the login, not BACK to the protected area, which would have immediately redirected AGAIN anyway.