React Router and Navigation

Setting Up React Router

React Router is the standard library for routing in React. It allows you to navigate between different views or pages in a single-page application (SPA).

Install React Router:

npm install react-router-dom

Basic setup example:


import { BrowserRouter, Routes, Route } from 'react-router-dom';
import Home from './pages/Home';
import About from './pages/About';

function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/about" element={<About />} />
      </Routes>
    </BrowserRouter>
  );
}
  

This creates a simple app with two routes: / and /about. Use the <Link /> component for navigation instead of regular anchor tags:


import { Link } from 'react-router-dom';

<nav>
  <Link to="/">Home</Link> | 
  <Link to="/about">About</Link>
</nav>
  

Dynamic Routing and Nested Routes

Dynamic Routes

React Router supports dynamic route parameters using : syntax.


<Route path="/user/:id" element={<UserProfile />} />
  

Inside the UserProfile component, use useParams() to access the route parameter:


import { useParams } from 'react-router-dom';

function UserProfile() {
  const { id } = useParams();
  return <h2>User ID: {id}</h2>;
}
  

Nested Routes

Nested routes allow components to be rendered inside parent layouts.


<Route path="/dashboard" element={<Dashboard />}>
  <Route path="settings" element={<Settings />} />
  <Route path="profile" element={<Profile />} />
</Route>
  

Inside the Dashboard component, render nested views using <Outlet />:


import { Outlet } from 'react-router-dom';

function Dashboard() {
  return (
    <div>
      <h1>Dashboard</h1>
      <Outlet />
    </div>
  );
}
  

Navigation Guards and Protected Routes

To protect certain routes (e.g., requiring authentication), create a wrapper component for authorization.

Example: Protected Route


import { Navigate } from 'react-router-dom';

function ProtectedRoute({ isAuthenticated, children }) {
  if (!isAuthenticated) {
    return <Navigate to="/login" replace />;
  }
  return children;
}
  

Use it like this:


<Route 
  path="/dashboard" 
  element={
    <ProtectedRoute isAuthenticated={userLoggedIn}>
      <Dashboard />
    </ProtectedRoute>
  } 
/>
  

This ensures that only authenticated users can access the /dashboard route.

Conclusion

React Router is a powerful and flexible library for managing navigation in your React apps. You’ve learned how to set up routes, handle dynamic and nested routes, and implement protected routes for authentication. In the next post, we’ll dive into state management in React — including local state, Context API, and external libraries like Redux.

Post a Comment

0 Comments