new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

React Router · Getting started · all subjects

routing/basics

146 notes in this subject, read out of this brain and free to use. This is page 1 of 3.

Create and render a router using RouterProvider

Create a router using createBrowserRouter() and pass it to the RouterProvider component to render your application. Import createBrowserRouter from 'react-router' and RouterProvider from 'react-router/dom'.

Data routers must not be held in React state

Data routers should not be held in React state. Create your router once outside of the React tree and pass it to RouterProvider. You can use patchRoutesOnNavigation to add additional routes programmatically.

Minimal React Router setup example

Example showing basic React Router setup: import React from "react"; import ReactDOM from "react-dom/client"; import { createBrowserRouter } from "react-router"; import { RouterProvider } from "react-router/dom"; const router = createBrowserRouter([ { path: "/", element: <div>Hello World</div>, }, ]); const root = document.getElementById("root"); ReactDOM.createRoot(root).render( <RouterProvider router={router} />, );

Data Mode navigation same as Framework Mode

Navigating in Data Mode is the same as Framework Mode. Users should refer to the Framework Mode Navigating guide for detailed information.

Route Object definition

Route Objects are the objects passed to createBrowserRouter. They define data loading, actions, revalidation, error boundaries, and more. The foundational structure uses at minimum a path and Component property.

Route Object lazy loading

Most properties in a route object can be lazily imported to reduce the initial bundle size. The lazy property is an async function that returns an object with properties like Component and loader, which can be loaded in parallel using Promise.all.

Middleware sequential execution

Middleware executes sequentially from parent routes to child routes. Each middleware receives a next function that continues down the chain. On the leaf route, the final next() call executes the loaders/actions.

Route Object Component property

The Component property in a route object defines the component that will render when the route matches. It receives the component function that displays the matched route's UI.

Route Object handle

Route handle allows apps to add anything to a route match in useMatches to create abstractions like breadcrumbs. It is an object that can store arbitrary metadata about a route.

Index routes definition

Index routes are defined by setting index: true on a route object without a path. Index routes render into their parent's Outlet at their parent's URL, acting as a default child route. Index routes cannot have children.

Minimal route configuration with createBrowserRouter

Routes are configured as the first argument to createBrowserRouter. At a minimum, you need a path and Component. Example: createBrowserRouter([{ path: "/", Component: Root }])

Nested routes with children

Routes can be nested inside parent routes through the children property. Child routes are rendered through the <Outlet/> component in the parent route. The parent's path is automatically included in child paths.

useParams hook for accessing dynamic segments

Dynamic segments are available in components through the useParams hook imported from react-router. This hook returns an object containing the parsed dynamic segment values from the current URL.

Dynamic segments in route paths

If a path segment starts with : then it becomes a dynamic segment. When the route matches a URL, the dynamic segment is parsed from the URL and provided as params to loaders, actions, and the useParams hook. Multiple dynamic segments can be in one route path.

Splat segments for catchall routes

If a route path pattern ends with /* then it will match any characters following the /, including other / characters. The matched portion is available as params["*"]. You can destructure it by assigning it a new name, commonly using: const { "*": splat } = params;

Prefix route for path grouping

A route with just a path and no component creates a group of routes with a path prefix. This groups related routes without introducing a layout component.

Layout routes without path

Omitting the path in a route creates nested routes for its children without adding any segments to the URL. This is useful for creating layout components that wrap multiple child routes.

createRoutesStub for testing routes

The createRoutesStub utility can be used for testing routes in both data and framework modes. Refer to the Testing Guide in the framework documentation for detailed information.

Wrap application with BrowserRouter

Wrap your application with the BrowserRouter component at the root level. Import BrowserRouter from react-router and render it around your App component in ReactDOM.createRoot().

BrowserRouter setup example

```tsx import React from "react"; import ReactDOM from "react-dom/client"; import { BrowserRouter } from "react-router"; import App from "./app"; const root = document.getElementById("root"); ReactDOM.createRoot(root).render( <BrowserRouter> <App /> </BrowserRouter>, ); ``` This example shows how to import BrowserRouter and wrap your App component with it.

NavLink active styling with children callback

NavLink children prop can accept a callback function that receives an object with an isActive boolean property for conditional rendering. Example: <NavLink to="/message">{({ isActive }) => <span className={isActive ? "active" : ""}>{isActive ? "👉" : ""} Tasks</span>}</NavLink>

NavLink example with end prop

NavLink accepts a to prop for the route path and an optional end prop. Example: <NavLink to="/" end>Home</NavLink> creates a navigation link to the home route.

NavLink active styling with style callback

NavLink style prop can accept a callback function that receives an object with an isActive boolean property. Example: <NavLink to="/messages" style={({ isActive }) => ({ color: isActive ? "red" : "black" })}>Messages</NavLink>

NavLink component renders active state

The NavLink component is used for navigation links that need to render an active state. When a NavLink is active, it automatically receives an .active class name for CSS styling. It also supports callback props on className, style, and children that receive an isActive parameter to enable inline styling or conditional rendering.

Link component example

Example usage of Link: <Link to="/login">Login again</Link> creates a simple navigation link without active state styling.

useNavigate use cases

Use useNavigate for situations where the user is not directly interacting with a navigation element, such as after a form submission completes, logging them out after inactivity, or timed UIs like quizzes. For normal navigation, Link or NavLink provide a better user experience with keyboard events, accessibility labeling, 'open in new window', and right-click context menus.

useNavigate hook example after form submission

Example of useNavigate after form submission: const navigate = useNavigate(); and then in the form's onSuccess callback: navigate("/dashboard");

useNavigate hook for programmatic navigation

The useNavigate hook allows programmatic navigation without user interaction. It should be imported from 'react-router'. The hook returns a navigate function that accepts a path string to navigate to that route.

Example: using location object for analytics and scroll restoration

function useAnalytics() { let location = useLocation(); useEffect(() => { sendFakeAnalytics(location.pathname); }, [location]); } function useScrollRestoration() { let location = useLocation(); useEffect(() => { fakeRestoreScroll(location.key); }, [location]); } This example shows how to use useLocation to access location.pathname for tracking analytics and location.key for restoring scroll position when the location changes.

Example: accessing route params

import { useParams } from "react-router"; function City() { let { city } = useParams(); let data = useFakeDataLibrary(`/api/v2/cities/${city}`); // ... } This example shows how to use useParams to destructure the city param from a dynamic route segment and use it to fetch data.

Location object with useLocation hook

React Router creates a custom location object with useful information that is accessible via the useLocation hook. The location object contains properties like pathname which holds the current path. This can be used in effects to perform actions like sending analytics or restoring scroll position based on URL changes.

URL search params with useSearchParams hook

Search params are the values after a '?' character in the URL. They are accessible from the useSearchParams hook, which returns an instance of URLSearchParams. To get a specific search param value, call the get method on the URLSearchParams object, for example searchParams.get('q') retrieves the query parameter named 'q'.

Route params with useParams hook

Route params are the parsed values from a dynamic segment in the route path. For example, in a route path like '/concerts/:city', the ':city' segment is dynamic. The parsed value for that segment is available from the useParams hook. When useParams is called in the component, it returns an object where you can destructure the param name, like let { city } = useParams().

Example: accessing search params

function SearchResults() { let [searchParams] = useSearchParams(); return ( <div> <p> You searched for <i>{searchParams.get("q")}</i> </p> <FakeSearchResults /> </div> ); } This example shows how to use useSearchParams to retrieve the query parameter 'q' from the URL's search string and display it.

Index routes definition

Index routes render into their parent's <Outlet/> at their parent's URL, acting like a default child route. They are configured with the index prop instead of a path prop. For example, <Route index element={<Home />} /> inside a parent route renders at the parent's URL.

Index routes cannot have children

Index routes cannot have children. If you're expecting that behavior, you probably want a layout route instead.

Layout routes without paths

Routes without a path prop create new nesting for their children but don't add any segments to the URL. This is useful for creating layout wrappers that apply to multiple routes. For example, <Route element={<MarketingLayout />}> with children <Route index element={<MarketingHome />} /> and <Route path="contact" element={<Contact />} /> will render the MarketingLayout for both the home page and /contact without the MarketingLayout being part of the URL path.

Outlet component for nested routes

Child routes render through the <Outlet/> component placed in the parent route component. For example, in a Dashboard component, you place <Outlet /> where child routes should render. The Outlet will be replaced by either <Home/> or <Settings/> depending on which child route matches.

Splat or catchall segments with asterisk

A splat or catchall segment is created by ending a route path pattern with "/*". This will match any characters following the "/", including other "/" characters. For example, <Route path="files/*" element={<File />} /> will match any path starting with "files/". Access the matched portion using useParams: let params = useParams(); let filePath = params["*"]; You can destructure and rename it: let { "*": splat } = useParams();

Nested routes in React Router

Routes can be nested inside parent routes. The path of the parent is automatically included in the child, so a <Route path="dashboard"> containing a <Route path="settings"> creates both "/dashboard" and "/dashboard/settings" URLs. Child routes are rendered through the <Outlet/> component placed in the parent route component.

Multiple dynamic segments in a route path

You can have multiple dynamic segments in one route path. For example, <Route path="/c/:categoryId/p/:productId" element={<Product />} /> creates two dynamic segments. Ensure that all dynamic segments in a given path are unique, otherwise the params object will have latter dynamic segment values override earlier values.

useParams hook for accessing dynamic segments

The useParams hook retrieves dynamic segment values from the current route. For example, in a component with route path="teams/:teamId", you can import { useParams } from "react-router"; and then let params = useParams(); to access params.teamId. You can destructure multiple dynamic segments: let { categoryId, productId } = useParams();

Route prefixes without elements

A <Route path> without an element prop adds a path prefix to its child routes without introducing a parent layout. For example, <Route path="projects"> containing <Route index element={<ProjectsHome />} /> adds the "projects" prefix to the routes without rendering any layout component.

Link and NavLink components for navigation

Use <Link> and <NavLink> from 'react-router' to link to routes from your UI. NavLink makes it easy to show active states by providing an isActive property in the className callback: <NavLink to="/" className={({ isActive }) => isActive ? "active" : ""}>. <Link to="/concerts/salt-lake-city"> is the basic link component.

BrowserRouter, Routes, Route setup

Routes are configured by rendering <Routes> and <Route> that couple URL segments to UI elements. The basic setup wraps your route configuration in <BrowserRouter>, which is imported from 'react-router'. A simple example: import React from "react"; import ReactDOM from "react-dom/client"; import { BrowserRouter, Routes, Route } from "react-router"; import App from "./app"; const root = document.getElementById("root"); ReactDOM.createRoot(root).render(<BrowserRouter><Routes><Route path="/" element={<App />} /></Routes></BrowserRouter>);

NavLink children function for pending UI

NavLink's children prop can be a function receiving {isPending}. This allows rendering pending state within the link text, such as displaying a spinner next to the link label when navigation is pending.

Global pending spinner with useNavigation

To display a global pending indicator during navigation, use useNavigation() to check if navigation.location is truthy. When true, show a spinner component, then render the Outlet component for the next page.

useNavigation hook for pending state

The useNavigation hook provides pending state information during navigation. The navigation.location property indicates when navigation is in progress. When navigation.location is truthy, the user is actively navigating to a new route.

NavLink with pending state functions

NavLink components can receive children, className, and style props as functions that receive an object with isPending property. This allows local pending indicators on individual links. When the link is pending, isPending is true.

Pending UI requires framework mode

Pending UI patterns using useNavigation and useFetcher are only available in framework mode of React Router, not in regular client-side router mode.

NavLink style prop with pending state

NavLink's style prop can be a function receiving {isPending} and returning a style object. This enables dynamic styling based on pending state, such as changing link color to gray while pending.

redirect function in loaders and actions

Inside route loaders and actions, you can return a redirect() to another URL. For example, checking if a user exists in a loader and redirecting to /login if they don't, or redirecting to a new record URL after creation in an action.

Form POST method with FormData

Forms with <Form method="post" /> will submit data as FormData instead of URLSearchParams. It is more common to use useFetcher() to POST form data.

Form component for URLSearchParams navigation

The Form component can be used to navigate with URLSearchParams. When a user submits a form with <Form action="/search"> and an input with name="q", they navigate to the action URL with query parameters, for example /search?q=journey.

Link component for non-active styled links

Use <Link> when the link doesn't need active styling. Link is imported from "react-router" and is a basic navigation component without state tracking.

NavLink example with active state styling

The end prop on NavLink (like <NavLink to="/" end>) indicates that the link should only be active when the route matches exactly. Multiple NavLink components can be used in a nav element to create navigation menus.

NavLink children callback props

NavLink supports children as a callback function that receives an object with isActive, isPending, and isTransitioning properties for conditional rendering.

NavLink style callback props

NavLink supports style as a callback function that receives an object with isActive, isPending, and isTransitioning properties for inline styling.

NavLink className callback props

NavLink supports className as a callback function that receives an object with isActive, isPending, and isTransitioning properties for inline styling or conditional rendering.

NavLink default CSS classes

NavLink automatically renders the following CSS classes: a.active for active links, a.pending for pending navigation, and a.transitioning when a CSS transition is running.

Give your agent this brain