tezvyn:

The <Route> Component: Mapping URLs to UI

AI-drafted, machine-checkedSource: reactrouter.comintermediate
The <Route> Component: Mapping URLs to UI

The <Route> component is like a switch statement for your UI, telling your app 'when the URL is X, render component Y'. It's used to define pages like `/dashboard` or `/users/:id`. The footgun is forgetting it must live inside a `<Routes>` component.

WHY IT EXISTS: Single-Page Applications (SPAs) need to mimic traditional multi-page websites by changing content based on the URL, but without full page reloads. React Router provides this client-side routing, and <Route> is the fundamental unit for declaring these URL-to-component mappings.

THE MENTAL MODEL: Think of <Route> as a conditional rendering rule. Its path prop is the condition to check against the browser's URL. Its element prop is the React component to render if the path matches. A set of these rules, nested inside a <Routes> component, creates a complete map of your application's pages.

HOW IT WORKS: When the location changes, the parent <Routes> component searches through its child <Route> elements to find the best match for the current URL. Once found, it renders the corresponding element. Path parameters, like :id in /invoices/:id, are parsed and made available to the matched component via the useParams hook. Routes can also define loader functions to fetch data and action functions to handle form submissions before the component renders.

WHEN TO USE IT: Use <Route> to define any view that corresponds to a specific URL. This is essential for creating pages, nested layouts, and dynamic content views. For example, you'd use a route for /dashboard, another for /settings, and a dynamic one for /products/:productId. You also use it to create 'layout routes' that render a shared shell with an <Outlet> for nested child routes to render into.

WHEN NOT TO USE IT: Do not use <Route> for conditional UI logic that is unrelated to the URL. If you need to show or hide a modal based on component state, use a standard JavaScript if condition. Also, <Route> defines the destination; to trigger navigation to that destination, use the <Link> component or the useNavigate hook.

ONE CANONICAL EXAMPLE: To map the URL path /profile/42 to a UserProfile component, you would write: <Route path="/profile/:userId" element={<UserProfile />} />. When a user visits that URL, React Router renders <UserProfile /> and the useParams hook within that component would return { userId: "42" }.

Read the original → reactrouter.com

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.