### Basic HashRouter Setup Source: https://reactrouter.com/6.30.3/router-components/hash-router Demonstrates the basic setup for using HashRouter in a React application. This is useful when server-side routing is not possible. ```tsx import * as React from "react"; import * as ReactDOM from "react-dom"; import { HashRouter } from "react-router-dom"; ReactDOM.render( {/* The rest of your app goes here */} , root ); ``` -------------------------------- ### Example Usage of createStaticRouter Source: https://reactrouter.com/6.30.3/routers/create-static-router An example demonstrating how to use createStaticRouter within a server-side rendering context. ```APIDOC ## Example Usage ### Description This example shows how to integrate `createStaticRouter` into a server-side rendering flow. ### Code ```jsx import { createStaticHandler, createStaticRouter, StaticRouterProvider, } from "react-router-dom/server"; import Root, { loader as rootLoader, ErrorBoundary as RootBoundary, } from "./root"; import ReactDOMServer from "react-dom/server"; const routes = [ { path: "/", loader: rootLoader, Component: Root, ErrorBoundary: RootBoundary, }, ]; // Assume createFetchRequest is defined elsewhere to handle request creation // declare function createFetchRequest(req: any): Request; export async function renderHtml(req) { let { query, dataRoutes } = createStaticHandler(routes); let fetchRequest = createFetchRequest(req); let context = await query(fetchRequest); if (context instanceof Response) { throw context; } let router = createStaticRouter(dataRoutes, context); return ReactDOMServer.renderToString( ); } ``` ``` -------------------------------- ### Bootstrap React App with Vite and Install Dependencies Source: https://reactrouter.com/6.30.3/start/tutorial Use this command to create a new React project with Vite, install React Router, and other tutorial-specific dependencies. Ensure you navigate into the project directory and run the development server. ```bash npm create vite@latest name-of-your-project -- --template react # follow prompts cd npm install react-router-dom # always need this! npm install localforage match-sorter sort-by # only for this tutorial. npm run dev ``` -------------------------------- ### Navigate Back/Forward with useNavigate (v6) Source: https://reactrouter.com/6.30.3/upgrading/v5 This v6 example demonstrates navigating back and forward using numerical arguments with the useNavigate hook. ```javascript import { useNavigate } from "react-router-dom"; function App() { const navigate = useNavigate(); return ( <> ); } ``` -------------------------------- ### Install React Router v6 Source: https://reactrouter.com/6.30.3/upgrading/reach Install the latest versions of react-router and react-router-dom. ```sh npm install react-router@6 react-router-dom@6 ``` -------------------------------- ### Create Hash Router Example Source: https://reactrouter.com/6.30.3/routers/create-hash-router Demonstrates how to create a hash router with nested routes. This is useful when server-side configuration for routing is not possible. ```tsx import * as React from "react"; import * as ReactDOM from "react-dom"; import { createHashRouter, RouterProvider, } from "react-router-dom"; import Root, { rootLoader } from "./routes/root"; import Team, { teamLoader } from "./routes/team"; const router = createHashRouter([ { path: "/", element: , loader: rootLoader, children: [ { path: "team", element: , loader: teamLoader, }, ], }, ]); ReactDOM.createRoot(document.getElementById("root")).render( ); ``` -------------------------------- ### Install Experimental React Router Releases Source: https://reactrouter.com/6.30.3/guides/contributing Add the '@next' tag to install the latest experimental build of React Router. This can be done with either pnpm or npm. ```bash pnpm add react-router-dom@next # or npm install react-router-dom@next ``` -------------------------------- ### Link Navigation Analogy to Filesystem Source: https://reactrouter.com/6.30.3/upgrading/v5 This example illustrates how relative `` values in v6 behave like `cd` commands in a filesystem, navigating up and down the route hierarchy. ```text // If your routes look like this // and the current URL is /app/dashboard (with or without // a trailing slash) => => => => // On the command line, if the current directory is /app/dashboard cd stats # pwd is /app/dashboard/stats cd ../stats # pwd is /app/stats cd ../../stats # pwd is /stats cd ../../../stats # pwd is /stats ``` -------------------------------- ### Example Usage of createStaticHandler Source: https://reactrouter.com/6.30.3/routers/create-static-handler Demonstrates how to use createStaticHandler within a server-side rendering context to fetch data and render HTML. ```APIDOC ## Example Usage ### Description This example shows how to use `createStaticHandler` to fetch data and render HTML on the server. ### Code ```jsx lines=[2,21-23] import { createStaticHandler, createStaticRouter, StaticRouterProvider, } from "react-router-dom/server"; import Root, { loader as rootLoader, ErrorBoundary as RootBoundary, } from "./root"; const routes = [ { path: "/", loader: rootLoader, Component: Root, ErrorBoundary: RootBoundary, }, ]; export async function renderHtml(req) { let { query, dataRoutes } = createStaticHandler(routes); let fetchRequest = createFetchRequest(req); let context = await query(fetchRequest); // If we got a redirect response, short circuit and let our Express server // handle that directly if (context instanceof Response) { throw context; } let router = createStaticRouter(dataRoutes, context); return ReactDOMServer.renderToString( ); } ``` ``` -------------------------------- ### Navigate Back/Forward with useHistory (v5) Source: https://reactrouter.com/6.30.3/upgrading/v5 This v5 example shows how to navigate back and forward using the go, goBack, and goForward methods from the useHistory hook. ```javascript import { useHistory } from "react-router-dom"; function App() { const { go, goBack, goForward } = useHistory(); return ( <> ); } ``` -------------------------------- ### Example: Resolving Action for useSubmit Source: https://reactrouter.com/6.30.3/hooks/use-form-action Illustrates how to use `useFormAction` to get the current route's action and pass it to `useSubmit` for form submissions. ```APIDOC ## Example: Resolving Action for `useSubmit` ### Description This example demonstrates how to use `useFormAction` to obtain the action for the current route and then pass this resolved action to the `submit` function from `useSubmit`. This ensures that form data is submitted to the correct endpoint. ### Usage ```jsx import { useSubmit, useFormAction } from "react-router-dom"; // Assume formData is available let submit = useSubmit(); let action = useFormAction(); submit(formData, { action }); ``` ### Explanation - `let action = useFormAction();` retrieves the default action for the current route. - `submit(formData, { action });` uses the retrieved action to send the `formData`. ``` -------------------------------- ### Mutation Form Submissions (PUT, DELETE) Source: https://reactrouter.com/6.30.3/components/form This example demonstrates handling mutation submissions (PUT, DELETE) within a route action. It shows how to get the request method and access form data. ```tsx } loader={async ({ params }) => { return fakeLoadProject(params.id); }} action={async ({ request, params }) => { switch (request.method) { case "PUT": { let formData = await request.formData(); let name = formData.get("projectName"); return fakeUpdateProject(name); } case "DELETE": { return fakeDeleteProject(params.id); } default: { throw new Response("", { status: 405 }); } } }} />; function Project() { let project = useLoaderData(); return ( <>
); } ``` -------------------------------- ### Install React Router v6 Source: https://reactrouter.com/6.30.3/upgrading/v5 Install React Router v6 using npm. Use react-router-dom for web apps and react-router-native for React Native apps. ```bash $ npm install react-router-dom # or, for a React Native app $ npm install react-router-native ``` -------------------------------- ### redirectDocument URL Parameter Example Source: https://reactrouter.com/6.30.3/fetch/redirectDocument Demonstrates the basic usage of redirectDocument with only the URL parameter to specify the redirection target. ```js redirectDocument("/otherapp/login"); ``` -------------------------------- ### Basic Link Usage Example Source: https://reactrouter.com/6.30.3/components/link Demonstrates how to use the Link component to create navigation links within a list. Ensure React and React Router DOM are imported. ```jsx import * as React from "react"; import { Link } from "react-router-dom"; function UsersIndexPage({ users }) { return (

Users

    {users.map((user) => (
  • {user.name}
  • ))}
); } ``` -------------------------------- ### React Router v5 App Structure Source: https://reactrouter.com/6.30.3/upgrading/v5 Example of a React Router v5 application structure demonstrating nested routes and links using match.url and match.path. ```javascript // This is a React Router v5 app import { BrowserRouter, Switch, Route, Link, useRouteMatch, } from "react-router-dom"; function App() { return ( ); } function Users() { // In v5, nested routes are rendered by the child component, so // you have elements all over your app for nested UI. // You build nested routes and links using match.url and match.path. let match = useRouteMatch(); return (
); } ``` -------------------------------- ### Example: Customizing Button FormAction Source: https://reactrouter.com/6.30.3/hooks/use-form-action Demonstrates how to use `useFormAction` to set the `formAction` for a button within a form, allowing it to trigger a specific action. ```APIDOC ## Example: Customizing Button FormAction ### Description This example shows how to use the `useFormAction` hook to dynamically set the `formAction` attribute of a submit button. This allows the button to submit to a specific action, overriding the default form action if necessary. ### Usage ```jsx import { useFormAction } from "react-router-dom"; function DeleteButton() { return ( ); } ``` ### Explanation - `useFormAction("destroy")` resolves the action to "destroy" relative to the current route. - `formAction` is set to the resolved action, making the button submit to the "destroy" action. - `formMethod="post"` specifies the HTTP method for the form submission. ``` -------------------------------- ### v6 Ranked Routes Example Source: https://reactrouter.com/6.30.3/start/faq This v6 example illustrates how route ranking automatically handles the correct matching of routes, even when a dynamic route like '/users/:id' is present. Specific routes like '/users/new' will rank higher. ```tsx function App() { return ( } /> } /> } /> ); } ``` -------------------------------- ### Full Route Tree Example Source: https://reactrouter.com/6.30.3/routers/create-browser-router Defines a complete route tree structure for a React Router application, including nested routes. ```javascript const routes = [ { path: "/", Component: Home, }, { id: "blog", path: "/blog", Component: BlogLayout, children: [ { path: "new", Component: NewPost }, { path: ":slug", Component: BlogPost }, ], }, ]; ``` -------------------------------- ### Clone and Setup React Router Repository Source: https://reactrouter.com/6.30.3/guides/contributing Clone your fork of the React Router repository and checkout the 'dev' branch for code changes. Ensure you are using pnpm for dependency management. ```bash git clone https://github.com//react-router.git cd react-router # if you are making *any* code changes, make sure to checkout the dev branch git checkout dev ``` -------------------------------- ### Basic BrowserRouter Setup Source: https://reactrouter.com/6.30.3/router-components/browser-router Sets up the BrowserRouter component to wrap the rest of your React application. Ensure you have a root element with id 'root' in your HTML. ```tsx import * as React from "react"; import { createRoot } from "react-dom/client"; import { BrowserRouter } from "react-router-dom"; const root = createRoot(document.getElementById("root")); root.render( {/* The rest of your app goes here */} ); ``` -------------------------------- ### React Router v6 App Structure Source: https://reactrouter.com/6.30.3/upgrading/v5 Example of a React Router v6 application structure showcasing relative routing and nested Routes. ```javascript // This is a React Router v6 app import { BrowserRouter, Routes, Route, Link, } from "react-router-dom"; function App() { return ( } /> } /> ); } function Users() { return (
} /> } />
); } ``` -------------------------------- ### Nested Route Element Tree Example Source: https://reactrouter.com/6.30.3/start/concepts Illustrates the React element tree structure that results from nested routes matching a specific URL. ```jsx ``` -------------------------------- ### Basic Routes Component Usage Source: https://reactrouter.com/6.30.3/components/routes Demonstrates the basic structure of the Routes component with a location prop. This is a foundational example for understanding how Routes accepts children. ```tsx interface RoutesProps { children?: React.ReactNode; location?: Partial | string; } ; ``` -------------------------------- ### Configure initialIndex for Memory Router Source: https://reactrouter.com/6.30.3/routers/create-memory-router The `initialIndex` option specifies which entry in the `initialEntries` array should be the starting point for the router. It defaults to the last entry. ```tsx createMemoryRouter(routes, { initialEntries: ["/", "/events/123"], initialIndex: 1, // start at "/events/123" }); ``` -------------------------------- ### Test an Event Route with createMemoryRouter Source: https://reactrouter.com/6.30.3/routers/create-memory-router This example demonstrates how to use `createMemoryRouter` to test a route with a loader function. It sets up initial entries and an initial index for the history stack. ```jsx import { RouterProvider, createMemoryRouter, } from "react-router-dom"; import * as React from "react"; import { render, waitFor, screen, } from "@testing-library/react"; import "@testing-library/jest-dom"; import CalendarEvent from "./routes/event"; test("event route", async () => { const FAKE_EVENT = { name: "test event" }; const routes = [ { path: "/events/:id", element: , loader: () => FAKE_EVENT, }, ]; const router = createMemoryRouter(routes, { initialEntries: ["/", "/events/123"], initialIndex: 1, }); render(); await waitFor(() => screen.getByRole("heading")); expect(screen.getByRole("heading")).toHaveTextContent( FAKE_EVENT.name ); }); ``` -------------------------------- ### Basic Form Submission Example Source: https://reactrouter.com/6.30.3/components/form Demonstrates a simple Form component usage for submitting data. Ensure all input elements have a 'name' attribute for their values to be included in the FormData. ```tsx import { Form } from "react-router-dom"; function NewEvent() { return (
); } ``` -------------------------------- ### Project File Structure Source: https://reactrouter.com/6.30.3/start/tutorial After setting up the project, ensure your 'src' directory contains only these essential files for the tutorial: 'contacts.js', 'index.css', and 'main.jsx'. ```text src ├── contacts.js ├── index.css └── main.jsx ``` -------------------------------- ### useSearchParams Hook Usage Source: https://reactrouter.com/6.30.3/hooks/use-search-params This example demonstrates how to use the `useSearchParams` hook to get the current search parameters and update them when a form is submitted. ```APIDOC ## useSearchParams Hook ### Description The `useSearchParams` hook is used to read and modify the query string in the URL for the current location. It returns an array containing the current search parameters and a function to update them. ### Usage ```tsx import * as React from "react"; import { useSearchParams } from "react-router-dom"; function App() { let [searchParams, setSearchParams] = useSearchParams(); function handleSubmit(event) { event.preventDefault(); // The serialize function here would be responsible for // creating an object of { key: value } pairs from the // fields in the form that make up the query. let params = serializeFormQuery(event.target); setSearchParams(params); } return (
{/* ... */}
); } ``` ### Type Declaration ```typescript declare function useSearchParams( defaultInit?: URLSearchParamsInit ): [URLSearchParams, SetURLSearchParams]; type ParamKeyValuePair = [string, string]; type URLSearchParamsInit = | string | ParamKeyValuePair[] | Record | URLSearchParams; type SetURLSearchParams = ( nextInit?: | URLSearchParamsInit | ((prev: URLSearchParams) => URLSearchParamsInit), navigateOpts?: : NavigateOptions ) => void; interface NavigateOptions { replace?: boolean; state?: any; preventScrollReset?: boolean; } ``` ### Notes - The `setSearchParams` function works similarly to `navigate`, but specifically for the search portion of the URL. - The second argument to `setSearchParams` is of the same type as the second argument to `navigate`. ``` -------------------------------- ### fetcher.load() Method Example Source: https://reactrouter.com/6.30.3/hooks/use-fetcher Call `fetcher.load()` to imperatively load data from a route loader. This is useful when data needs to be fetched based on component state or lifecycle events. ```tsx import { useFetcher } from "react-router-dom"; function SomeComponent() { const fetcher = useFetcher(); useEffect(() => { if (fetcher.state === "idle" && !fetcher.data) { fetcher.load("/some/route"); } }, [fetcher]); return
{fetcher.data || "Loading..."}
; } ``` -------------------------------- ### Filter List Data in Loader for GET Submissions Source: https://reactrouter.com/6.30.3/start/tutorial Implement data filtering within the `loader` function when using GET form submissions. This approach is suitable because GET requests only change the URL, similar to a link click, and do not invoke an `action`. ```jsx export async function loader({ request }) { const url = new URL(request.url); const q = url.searchParams.get("q"); const contacts = await getContacts(q); return { contacts }; } ``` -------------------------------- ### Install @reach/router v1.3.3 Source: https://reactrouter.com/6.30.3/upgrading/reach Install the latest version of @reach/router to prepare for the React Router v6 upgrade. This step should be followed by deploying the application. ```sh npm install @reach/router@latest ``` -------------------------------- ### Reach Router Redirect Example Source: https://reactrouter.com/6.30.3/upgrading/reach This example shows the syntax for redirects in the older @reach/router library, which is no longer supported in React Router v6. ```jsx ``` -------------------------------- ### Get Navigation Type Source: https://reactrouter.com/6.30.3/hooks/use-navigation-type Use the useNavigationType hook to get the current navigation action. This hook returns one of 'POP', 'PUSH', or 'REPLACE'. ```tsx import { useNavigationType } from "react-router-dom"; function MyComponent() { const navigationType = useNavigationType(); return (

You arrived here via: {navigationType}

); } ``` -------------------------------- ### createMemoryRouter Usage Source: https://reactrouter.com/6.30.3/routers/create-memory-router Demonstrates how to use `createMemoryRouter` with initial entries and an initial index for testing. ```APIDOC ## `createMemoryRouter` ### Description Creates a router that manages its history stack in memory, useful for testing and non-browser environments. ### Method Signature ```typescript function createMemoryRouter(routes: RouteObject[], opts?: { basename?: string; future?: FutureConfig; hydrationData?: HydrationState; initialEntries?: InitialEntry[]; initialIndex?: number; }): RemixRouter; ``` ### Parameters #### `routes` - **RouteObject[]** - An array of route objects defining the application's routes. #### `opts` (Optional) - **`basename`** (string) - The base URL for the router. - **`future`** (FutureConfig) - Future configuration options. - **`hydrationData`** (HydrationState) - Data for hydration. - **`initialEntries`** (InitialEntry[]) - The initial entries in the history stack. Allows starting with multiple locations. Example: ```typescript createMemoryRouter(routes, { initialEntries: ["/", "/events/123"], }); ``` - **`initialIndex`** (number) - The initial index in the history stack to render. Defaults to the last entry in `initialEntries`. Example: ```typescript createMemoryRouter(routes, { initialEntries: ["/", "/events/123"], initialIndex: 1, // start at "/events/123" }); ``` ### Returns - **RemixRouter** - The created memory router instance. ``` -------------------------------- ### Basic RouterProvider Usage Source: https://reactrouter.com/6.30.3/routers/router-provider Demonstrates how to create a browser router and render the application using RouterProvider. Includes a fallback element for initial loading. ```jsx import { createBrowserRouter, RouterProvider, } from "react-router-dom"; const router = createBrowserRouter([ { path: "/", element: , children: [ { path: "dashboard", element: , }, { path: "about", element: , }, ], }, ]); ReactDOM.createRoot(document.getElementById("root")).render( } /> ); ``` -------------------------------- ### Root Application Rendering with Routes Source: https://reactrouter.com/6.30.3/start/concepts This is the entry point of a React application, setting up the main routing structure with nested routes. ```jsx const root = ReactDOM.createRoot( document.getElementById("root") ); root.render( }> } /> }> } /> } /> } /> }> } /> } /> } /> ); ``` -------------------------------- ### Ranked Route Matching Example Source: https://reactrouter.com/6.30.3/start/overview React Router prioritizes more specific routes. In this example, `/teams/new` is preferred over `/teams/:teamId` for the URL `/teams/new` because it has more static segments. ```jsx ``` -------------------------------- ### Basic Client-Side Routing Setup Source: https://reactrouter.com/6.30.3/start/overview Sets up a basic client-side router with two routes: a home page and an about page. Use this to enable navigation within your React application without server requests. ```jsx import * as React from "react"; import { createRoot } from "react-dom/client"; import { createBrowserRouter, RouterProvider, Route, Link, } from "react-router-dom"; const router = createBrowserRouter([ { path: "/", element: (

Hello World

About Us
), }, { path: "about", element:
About
, }, ]); createRoot(document.getElementById("root")).render( ); ``` -------------------------------- ### GET Form Submission Source: https://reactrouter.com/6.30.3/components/form Use this snippet for forms that navigate the user and update the URL with search parameters without calling an action. The default method is 'get'. ```tsx
``` -------------------------------- ### React Router v5 Route Composition Example Source: https://reactrouter.com/6.30.3/start/faq In v5, `` components rendered directly and could contain other routes. This example shows a `MyRoute` component rendering a `` with children. ```tsx let App = () => (
); let MyRoute = ({ element, ...rest }) => { return ( Hello!

} /> ); }; ``` -------------------------------- ### Create and Render Browser Router in main.jsx Source: https://reactrouter.com/6.30.3/start/tutorial Sets up the main entry point for the application with React Router. It creates a browser router and renders the application within it. This is the first step to enable client-side routing. ```jsx import * as React from "react"; import * as ReactDOM from "react-dom/client"; import { createBrowserRouter, RouterProvider, } from "react-router-dom"; import "./index.css"; const router = createBrowserRouter([ { path: "/", element:
Hello world!
, }, ]); ReactDOM.createRoot(document.getElementById("root")).render( ); ``` -------------------------------- ### fetcher.submit() Method Example Source: https://reactrouter.com/6.30.3/hooks/use-fetcher Use `fetcher.submit()` for imperative form submissions, typically when the submission is initiated programmatically rather than by direct user interaction. This example shows logging out a user after a period of inactivity. ```tsx import { useFetcher } from "react-router-dom"; import { useFakeUserIsIdle } from "./fake/hooks"; export function useIdleLogout() { const fetcher = useFetcher(); const userIsIdle = useFakeUserIsIdle(); useEffect(() => { if (userIsIdle) { fetcher.submit( { idle: true }, { method: "post", action: "/logout" } ); } }, [userIsIdle]); } ``` -------------------------------- ### Accessing GET Parameters in Loader Source: https://reactrouter.com/6.30.3/components/form This snippet shows how to access URL search parameters within a route loader when using a GET form submission. It demonstrates creating a URL object from the request. ```tsx { let url = new URL(request.url); let searchTerm = url.searchParams.get("q"); return fakeSearchProducts(searchTerm); }} /> ``` -------------------------------- ### Configuring Routes with Error Handling Source: https://reactrouter.com/6.30.3/hooks/use-route-error Demonstrates how to set up an `errorElement` for a route and includes examples of potential errors that can occur in loaders, actions, and during rendering. Errors thrown in actions can be `Response` objects. ```jsx } loader={() => { // unexpected errors in loaders/actions something.that.breaks(); }} action={() => { // stuff you throw on purpose in loaders/actions throw new Response("Bad Request", { status: 400 }); }} element={ // and errors thrown while rendering
{breaks.while.rendering}
} /> ``` -------------------------------- ### Use
for Client-Side GET Submissions Source: https://reactrouter.com/6.30.3/start/tutorial Replace HTML's `` with React Router's `` component to enable client-side routing for GET requests. This component handles the form submission by changing the URL. ```jsx