} />
);
};
```
--------------------------------
### 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
```
--------------------------------
### Server-Side Rendering with createStaticHandler
Source: https://reactrouter.com/6.30.3/routers/create-static-handler
This example demonstrates how to use createStaticHandler to fetch data and handle submissions on the server before rendering the React application. It includes setting up routes, creating a fetch request, querying data, and rendering the application using StaticRouterProvider. If a redirect response is encountered, it's thrown to be handled by the server.
```jsx
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(
);
}
```
--------------------------------
### Create Express Server Handler
Source: https://reactrouter.com/6.30.3/guides/ssr
Set up an Express server to handle incoming requests. Use `createStaticHandler` to initialize the data router handler with your defined routes.
```jsx
const express = require("express");
const {
createStaticHandler,
} = require("react-router-dom/server");
const createFetchRequest = require("./request");
const routes = require("./routes");
const app = express();
let handler = createStaticHandler(routes);
app.get("*", async (req, res) => {
let fetchRequest = createFetchRequest(req, res);
let context = await handler.query(fetchRequest);
// We'll tackle rendering next...
});
const listener = app.listen(3000, () => {
let { port } = listener.address();
console.log(`Listening on port ${port}`);
});
```
--------------------------------
### Automatic Logout Example
Source: https://reactrouter.com/6.30.3/hooks/use-submit
Illustrates using `useSubmit` to automatically log out a user after a period of inactivity.
```APIDOC
## useSubmit with Timeout
### Description
This example shows how to use `useSubmit` within a custom hook to trigger an action after a set delay, simulating an automatic logout after user inactivity.
### Example
```tsx lines=[1,10,15]
import { useSubmit, useLocation } from "react-router-dom";
import { useEffect } from "react";
function AdminPage() {
useSessionTimeout();
return
{/* ... */}
;
}
function useSessionTimeout() {
const submit = useSubmit();
const location = useLocation();
useEffect(() => {
const timer = setTimeout(() => {
submit(null, { method: "post", action: "/logout" });
}, 5 * 60_000); // 5 minutes
return () => clearTimeout(timer);
}, [submit, location]);
}
```
### Submit Target
In this example, `submit(null, ...)` is used, indicating no specific form element is being submitted directly, but rather a navigation action is being triggered.
### Submit Options
- `method`: "post"
- `action`: "/logout"
This configuration triggers a POST request to the `/logout` endpoint after the timeout.
```
--------------------------------
### Basic useFetcher Usage
Source: https://reactrouter.com/6.30.3/hooks/use-fetcher
Demonstrates how to import and use the `useFetcher` hook. It shows calling `submit` or `load` within a `useEffect` and accessing fetcher properties like `state`, `data`, and rendering a `` for non-navigating submissions.
```tsx
import { useFetcher } from "react-router-dom";
function SomeComponent() {
const fetcher = useFetcher();
// call submit or load in a useEffect
React.useEffect(() => {
fetcher.submit(data, options);
fetcher.load(href);
}, [fetcher]);
// build your UI with these properties
fetcher.state;
fetcher.formData;
fetcher.json;
fetcher.text;
fetcher.formMethod;
fetcher.formAction;
fetcher.data;
// render a form that doesn't cause navigation
return ;
}
```
--------------------------------
### Create a Browser Router with Routes
Source: https://reactrouter.com/6.30.3/routers/create-browser-router
Use `createBrowserRouter` to set up routing for your web application. Define your routes, including nested routes and their associated loaders, and then pass the router instance to `RouterProvider`.
```tsx
import * as React from "react";
import * as ReactDOM from "react-dom";
import {
createBrowserRouter,
RouterProvider,
} from "react-router-dom";
import Root, { rootLoader } from "./routes/root";
import Team, { teamLoader } from "./routes/team";
const router = createBrowserRouter([
{
path: "/",
element: ,
loader: rootLoader,
children: [
{
path: "team",
element: ,
loader: teamLoader,
},
],
},
]);
ReactDOM.createRoot(document.getElementById("root")).render(
);
```
--------------------------------
### Import and Use useActionData Hook
Source: https://reactrouter.com/6.30.3/hooks/use-action-data
Import the hook from 'react-router-dom' and call it within your component to get the action data.
```tsx
import { useActionData } from "react-router-dom";
function SomeComponent() {
let actionData = useActionData();
// ...
}
```
--------------------------------
### Enabling Future Flags with `createStaticRouter` Options
Source: https://reactrouter.com/6.30.3/routers/create-static-router
This example shows how to enable future flags, such as `v7_partialHydration`, when creating a static router. This is recommended for adopting new features and easing migration to future versions.
```js
const router = createBrowserRouter(routes, {
future: {
// Opt-into partial hydration
v7_partialHydration: true,
},
});
```
--------------------------------
### Update to Latest v6
Source: https://reactrouter.com/6.30.3/upgrading/future
Install the latest minor version of React Router DOM to access the newest future flags.
```shellscript
npm install react-router-dom@6
```
--------------------------------
### Creating a Browser Router with Dynamic Route Patching
Source: https://reactrouter.com/6.30.3/routers/create-browser-router
Initializes a browser router with a minimal set of routes and configures `patchRoutesOnNavigation` to dynamically add routes based on the navigation path.
```javascript
const router = createBrowserRouter(
[
{
path: "/",
Component: Home,
},
],
{
patchRoutesOnNavigation({ path, patch }) {
if (path === "/blog/new") {
patch("blog", [
{
path: "new",
Component: NewPost,
},
]);
} else if (path.startsWith("/blog")) {
patch("blog", [
{
path: ":slug",
Component: BlogPost,
},
]);
}
},
}
);
```
--------------------------------
### v5 Nested Routes Example
Source: https://reactrouter.com/6.30.3/start/faq
Demonstrates how nested routes were handled in React Router v5 using `` components.
```tsx
function Users() {
return (
Users
);
}
```
```tsx
// somewhere up the tree
;
```
--------------------------------
### Basic App Structure with Routes
Source: https://reactrouter.com/6.30.3/upgrading/v6-data
This is a typical React application structure using BrowserRouter and Routes to define application routes.
```jsx
export default function App() {
return (
My Super Cool App
} />
} />
} />
);
}
```
--------------------------------
### Form Component Usage
Source: https://reactrouter.com/6.30.3/components/form
Example of how to use the Form component to submit data. Ensure inputs have names for FormData inclusion.
```APIDOC
## `
);
}
```
### Props
This component accepts standard HTML form attributes, plus additional props for routing:
- `method`: HTTP method for the form submission (`get`, `post`, `put`, `patch`, `delete`). Defaults to `get`.
- `encType`: Encoding type for the form data (`application/x-www-form-urlencoded`, `multipart/form-data`, `text/plain`).
- `action`: The URL to submit the form data to.
- `onSubmit`: A handler for the form's submit event.
- `fetcherKey`: A key for the fetcher.
- `navigate`: If true, the form submission will trigger a navigation.
- `preventScrollReset`: If true, prevents the scroll position from resetting on navigation.
- `relative`: Defines the navigation relativity (`route` or `path`).
- `reloadDocument`: If true, the document will be reloaded on submission.
- `replace`: If true, the navigation will replace the current entry in the history stack.
- `state`: Any state to be passed with the navigation.
- `viewTransition`: If true, enables view transitions for the submission.
### Notes
- Inputs within the Form component must have a `name` attribute for their values to be included in the `FormData`.
- This feature requires a data router to be configured.
- Use `useNavigation` to monitor submission status and build pending indicators.
- For non-navigation related data mutations, consider using `useFetcher`.
```
--------------------------------
### Simple URL Redirect
Source: https://reactrouter.com/6.30.3/fetch/redirect
Demonstrates the basic usage of the `redirect` function with just a URL string.
```js
redirect("/login");
```
--------------------------------
### Custom Link Component with useLinkPressHandler
Source: https://reactrouter.com/6.30.3/hooks/use-link-press-handler
Example of creating a custom Link component using the useLinkPressHandler hook for navigation in react-router-native.
```tsx
import { TouchableHighlight } from "react-native";
import { useLinkPressHandler } from "react-router-native";
function Link({
onPress,
replace = false,
state,
to,
...rest
}) {
let handlePress = useLinkPressHandler(to, {
replace,
state,
});
return (
{
onPress?.(event);
if (!event.defaultPrevented) {
handlePress(event);
}
}}
/>
);
}
```
--------------------------------
### Render HTML with StaticRouterProvider
Source: https://reactrouter.com/6.30.3/guides/ssr
After fetching data, create a static router and render the application to HTML using `ReactDOMServer.renderToString`. This HTML is sent to the client.
```jsx
app.get("*", async (req, res) => {
let fetchRequest = createFetchRequest(req, res);
let context = await handler.query(fetchRequest);
let router = createStaticRouter(
handler.dataRoutes,
context
);
let html = ReactDOMServer.renderToString(
);
res.send("" + html);
});
```
--------------------------------
### Create Edit Component File
Source: https://reactrouter.com/6.30.3/start/tutorial
Use the `touch` command to create a new JSX file for the edit component.
```bash
touch src/routes/edit.jsx
```
--------------------------------
### Import and Use useFetchers
Source: https://reactrouter.com/6.30.3/hooks/use-fetchers
Import and use the useFetchers hook to get an array of inflight fetchers. This feature requires a data router.
```tsx
import { useFetchers } from "react-router-dom";
function SomeComp() {
const fetchers = useFetchers();
// array of inflight fetchers
}
```
--------------------------------
### Enable Fetcher Persistence with future.v7_fetcherPersist
Source: https://reactrouter.com/6.30.3/start/changelog
Opt into the new fetcher persistence behavior by setting the `future.v7_fetcherPersist` flag. Fetchers will now remain mounted until they return to an `idle` state, simplifying pending UI.
```javascript
{
future: {
v7_fetcherPersist: true
}
}
```
--------------------------------
### Configure Route Action in React Router
Source: https://reactrouter.com/6.30.3/start/tutorial
Imports and assigns the root action to the root route configuration within the createBrowserRouter setup.
```jsx
/* other imports */
import Root, {
loader as rootLoader,
action as rootAction,
} from "./routes/root";
const router = createBrowserRouter([
{
path: "/",
element: ,
errorElement: ,
loader: rootLoader,
action: rootAction,
children: [
{
path: "contacts/:contactId",
element: ,
},
],
},
]);
```
--------------------------------
### Express Server for SSR
Source: https://reactrouter.com/6.30.3/guides/ssr
A basic Express server setup that uses `ReactDOMServer.renderToString` and `StaticRouter` to render the React application on the server. It handles incoming requests and sends back the rendered HTML.
```javascript
import express from "express";
import ReactDOMServer from "react-dom/server";
import { StaticRouter } from "react-router-dom/server";
import App from "./App";
let app = express();
app.get("*", (req, res) => {
let html = ReactDOMServer.renderToString(
);
res.send("" + html);
});
app.listen(3000);
```
--------------------------------
### Configure initialEntries for Memory Router
Source: https://reactrouter.com/6.30.3/routers/create-memory-router
The `initialEntries` option allows you to pre-populate the history stack with multiple locations, useful for testing navigation scenarios like going back.
```tsx
createMemoryRouter(routes, {
initialEntries: ["/", "/events/123"],
});
```
--------------------------------
### Programmatic Form Submission with useSubmit
Source: https://reactrouter.com/6.30.3/hooks/use-submit
Use `useSubmit` to programmatically submit a form, for example, on input change. This hook requires a data router.
```tsx
import { useSubmit, Form } from "react-router-dom";
function SearchField() {
let submit = useSubmit();
return (
);
}
```
--------------------------------
### Redirect as a Response Shortcut
Source: https://reactrouter.com/6.30.3/fetch/redirect
Illustrates that `redirect` is a syntactic sugar for creating a `Response` object with specific status and headers for redirection.
```jsx
new Response("", {
status: 302,
headers: {
Location: someUrl,
},
});
```
--------------------------------
### useAsyncError Usage
Source: https://reactrouter.com/6.30.3/hooks/use-async-error
This example demonstrates how to use the useAsyncError hook within an error element to display an error message when a deferred route fails.
```APIDOC
## `useAsyncError` Hook
### Description
Returns the rejection value from the nearest `` component. This is useful for displaying error messages when asynchronous data loading fails.
### Usage
```tsx
import { useAsyncError, Await } from "react-router-dom";
function ErrorElement() {
const error = useAsyncError();
return (
Uh Oh, something went wrong! {error.message}
);
}
}
/>;
```
### Related Links
- [Deferred Data Guide][deferred]
- [`` documentation][await docs]
[await docs]: ../components/await
[deferred]: ../guides/deferred
```
--------------------------------
### Accessing navigation.formMethod
Source: https://reactrouter.com/6.30.3/hooks/use-navigation
Use `navigation.formMethod` to access the submission method (e.g., 'POST') when navigating from a `
);
}
```
--------------------------------
### Create Contact Route Module
Source: https://reactrouter.com/6.30.3/start/tutorial
Use the touch command to create a new JSX file for the contact route component.
```sh
touch src/routes/contact.jsx
```