React

React Router Tutorial

Learn how to implement client-side routing in your React application using React Router v6.

Introduction to React Router

React Router is the standard solution for routing in React apps. It lets you manage multiple pages and navigation within a single-page application (SPA) without full page reloads.

Client-Side Routing

Seamless navigation without full page reloads.

Nested Routes

Organize components with route-based layouts.

Dynamic URLs

Define routes with URL parameters.

Key Concepts

  • BrowserRouter for SPA mode
  • Routes for defining routes
  • Route for individual route components
  • Link for navigation without full refresh
react-router-dom v6.22.0+

Installation


npm install react-router-dom

                

Import and wrap your app with BrowserRouter in your main component.

import { BrowserRouter as Router, Routes, Route } from "react-router-dom"; function App() { return ( {/* Routes go here */} ); }

Basic Routing Example

Create Routes

import { Route, Routes } from "react-router-dom"; import Home from "./components/Home"; import About from "./components/About"; return ( } /> } /> 404
} /> );

Navigation

import { Link } from "react-router-dom"; Home | About

Nested Routes

Use nested routing to create layouts that persist across child routes.

// Layout component function DashboardLayout({ children }) { return (

Dashboard

{children}
); } // In routes } > } /> } />

The children prop will render the matched child route inside this component.

Dynamic URL Parameters

// User Profile Route } /> // Access param: function User() { const { id } = useParams(); return
User {id}
; }

Path:

/users/123

Params:

{ id: "123" }

Full Router Example

import { BrowserRouter as Router, Routes, Route, Link, useParams } from 'react-router-dom'; function Home() { return
Home Page
; } function About() { return
About Page
; } function User() { const { id } = useParams(); return
User ID: {id}
; } function App() { return ( } /> } /> } /> ); }

Try a Demo

Click navigation links to see routing in action