SyntaxStudy
Sign Up
React React Router v6 Basics
React Beginner 1 min read

React Router v6 Basics

React Router v6 is the standard client-side routing library for React applications. You wrap your application in BrowserRouter, which reads the browser URL and provides routing context to the entire tree. Inside BrowserRouter you place a single Routes element that acts as a switch, rendering the first Route whose path matches the current location. Routes in v6 are declared with the Route component. The path prop supports dynamic segments prefixed with a colon, such as /users/:id, and wildcard segments with an asterisk. Nested routes are expressed by nesting Route elements and rendering an Outlet in the parent component where children should appear, which eliminates the need for the exact prop that was required in v5. Navigation is handled declaratively with the Link component, which renders an accessible anchor tag, or programmatically with the useNavigate hook. Avoid using the native anchor element for in-app navigation because it triggers a full page reload and discards all React state.
Example
import { BrowserRouter, Routes, Route, Link, Outlet } from 'react-router-dom';

// ── Pages ──────────────────────────────────────────────────────────────────
function Home()    { return <h1>Home</h1>; }
function About()   { return <h1>About</h1>; }
function NotFound(){ return <h1>404 – Not Found</h1>; }

// ── Layout with shared navigation ─────────────────────────────────────────
function Layout() {
    return (
        <>
            <nav>
                <Link to="/">Home</Link>{' | '}
                <Link to="/about">About</Link>{' | '}
                <Link to="/users">Users</Link>
            </nav>
            <main>
                <Outlet /> {/* child routes render here */}
            </main>
        </>
    );
}

// ── Route tree ─────────────────────────────────────────────────────────────
export default function App() {
    return (
        <BrowserRouter>
            <Routes>
                <Route path="/" element={<Layout />}>
                    <Route index element={<Home />} />
                    <Route path="about" element={<About />} />
                    <Route path="users" element={<UserList />} />
                    <Route path="users/:id" element={<UserDetail />} />
                    <Route path="*" element={<NotFound />} />
                </Route>
            </Routes>
        </BrowserRouter>
    );
}