React Router

7.14.1 · active · verified Sat Apr 18

React Router is the core library for declarative routing in React applications, providing the foundational hooks and utilities for navigation and state management. The current stable version is 7.14.1, with frequent point releases reflecting active development and maintenance.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to set up a basic data router with `createBrowserRouter` and `RouterProvider`, defining nested routes and using `Link` for declarative navigation and `useNavigate` for programmatic navigation within a React application.

import React from 'react';
import ReactDOM from 'react-dom/client';
import {
  createBrowserRouter,
  RouterProvider,
  Outlet,
  Link,
  useNavigate
} from 'react-router';

function Layout() {
  const navigate = useNavigate();
  return (
    <div>
      <h1>React Router Example</h1>
      <nav>
        <Link to="/">Home</Link> | <Link to="/about">About</Link>
      </nav>
      <hr />
      <Outlet /> {/* Renders the current route's element */}
      <button onClick={() => navigate('/contact')}>Go to Contact</button>
    </div>
  );
}

function HomePage() {
  return <h2>Welcome to the Home Page!</h2>;
}

function AboutPage() {
  return <h2>Learn more about us!</h2>;
}

function ContactPage() {
  return <h2>Get in touch!</h2>;
}

const router = createBrowserRouter([
  {
    path: '/',
    element: <Layout />,
    children: [
      {
        index: true,
        element: <HomePage />,
      },
      {
        path: 'about',
        element: <AboutPage />,
      },
      {
        path: 'contact',
        element: <ContactPage />,
      },
    ],
  },
]);

ReactDOM.createRoot(document.getElementById('root')!).render(
  <React.StrictMode>
    <RouterProvider router={router} />
  </React.StrictMode>
);

view raw JSON →