TutorialsReactReact Routing
Share:

React Routing

advanced

Part of Advanced React

Theory

React Router is the standard routing library for React applications. It enables client-side routing in SPAs, allowing navigation between views without full page reloads.

Core Components

  • <BrowserRouter> — wraps the app and enables routing
  • <Routes> / <Route> — defines URL-to-component mappings
  • <Link> — declarative navigation (renders an <a> tag)
  • <NavLink> — like <Link> with active state styling

Dynamic Parameters

Use :param in route paths (e.g., /users/:id). Access parameters via the useParams() hook.

Nested Routes

Nested routes create layouts with persistent UI. The parent route renders an <Outlet /> where child routes are rendered.

Programmatic Navigation

Use the useNavigate() hook to navigate imperatively — after form submission, authentication redirects, or timeouts.

Practical Examples

Example 1: Basic Routing Setup
jsx
Example 2: Dynamic Routes and Nested Routes
jsx

Exercises

Product Detail Page with Routing

medium

Set up a React Router with a Products page that lists products and a ProductDetail page that shows details for a single product using dynamic routing with :id. Use Link to navigate and useParams to get the id.

Expected Output:

Clicking a product shows its detail page with the correct id

Mini Quiz

Mini Quiz