React Router v6 – Basic and Dynamic Routing

In a single-page application (SPA) built with React, routing is essential to create a multi-page experience without refreshing the browser. React Router v6 is the most popular and powerful routing solution for React applications, allowing seamless navigation and dynamic content loading.

This module dives deep into basic routing, nested routes, dynamic routes, and route parameters using React Router v6.


1. What is React Router?

React Router is a standard library for routing in React. It enables navigation among views of various components, allows browser URL changes, and keeps the UI in sync with the URL.

React Router v6 introduced a simpler, more declarative API, better nested route handling, and performance improvements over previous versions.


2. Installation

To use React Router in a React project:

npm install react-router-dom

Then, in your main file (usually main.jsx or index.jsx), wrap your app in the BrowserRouter component:

import { BrowserRouter } from 'react-router-dom';
import App from './App';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<BrowserRouter>
<App />
</BrowserRouter>
);

3. Basic Routing Setup

Here’s how to define basic routes:

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

function App() {
return (
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
);
}
  • Routes is the new component that replaces Switch from v5.
  • element replaces component and takes JSX.

To create navigation links:

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

function Navbar() {
return (
<nav>
<Link to="/">Home</Link> | <Link to="/about">About</Link>
</nav>
);
}

4. Nested Routes

React Router v6 makes nested routes easier and more intuitive:

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

Inside the Dashboard component, use the Outlet component to render nested children:

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

const Dashboard = () => {
return (
<div>
<h2>Dashboard</h2>
<Outlet />
</div>
);
};

5. Dynamic Routes with Parameters

Dynamic routing allows you to match patterns like /users/:id to render user-specific pages.

<Route path="/users/:userId" element={<UserProfile />} />

Inside the UserProfile component, access the parameter using useParams:

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

const UserProfile = () => {
const { userId } = useParams();
return <h2>User Profile for ID: {userId}</h2>;
};

You can use multiple parameters like /teams/:teamId/members/:memberId and access them similarly.


6. Navigation Programmatically

To navigate programmatically (e.g., after a form submission or authentication), use useNavigate:

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

const Login = () => {
const navigate = useNavigate();

const handleLogin = () => {
// Logic to log in
navigate('/dashboard');
};

return <button onClick={handleLogin}>Log In</button>;
};

7. Fallback Routes (404 Handling)

You can catch undefined routes using a wildcard path:

<Route path="*" element={<NotFound />} />

This is typically added at the end of your route definitions to show a custom 404 page.


8. Best Practices for Routing

  • Use Link instead of anchor tags to prevent full-page reloads.
  • Group and modularize your routes when your app grows.
  • Prefer nested routes to avoid repetition and simplify layouts.
  • Use lazy loading (via React.lazy) for route-based code-splitting.

9. Code Example: Putting It All Together

// App.jsx
import { Routes, Route, Link } from 'react-router-dom';
import Home from './pages/Home';
import About from './pages/About';
import User from './pages/User';

export default function App() {
return (
<div>
<nav>
<Link to="/">Home</Link> | <Link to="/about">About</Link> | <Link to="/users/42">User</Link>
</nav>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/users/:userId" element={<User />} />
<Route path="*" element={<h2>404 - Page Not Found</h2>} />
</Routes>
</div>
);
}
// User.jsx
import { useParams } from 'react-router-dom';

export default function User() {
const { userId } = useParams();
return <div>Viewing profile of user with ID: {userId}</div>;
}

Conclusion

React Router v6 brings a powerful, intuitive, and flexible routing system to your React apps. It supports everything from basic navigation to deeply nested dynamic routes, making it ideal for both small and large applications.