React Router is a collection of React components, hooks and utilities that make it easy to build multi-page applications with React. This reference contains the function signatures and return types of the various interfaces in React Router.
Tip:
Please refer to our guides for more in-depth usage examples of how you can use React Router to accomplish specific tasks.
React Router is published to npm in three different packages:
react-routercontains most of the core functionality of React Router including the route matching algorithm and most of the core components and hooksreact-router-domincludes everything fromreact-routerand adds a few DOM-specific APIs like<BrowserRouter>,<HashRouter>,<Link>, etc.react-router-nativeincludes everything fromreact-routerand adds a few APIs that are specific to React Native including<NativeRouter>and a native version of<Link>
Both react-router-dom and react-router-native automatically include react-router as a dependency when you install them, and both packages re-export everything from react-router. When you import stuff, you should always import from either react-router-dom or react-router-native and never directly from react-router. Otherwise you may accidentally import mismatched versions of the library in your app.
If you installed React Router as a global (using a <script> tag), you can find the library on the window.ReactRouterDOM object. If you installed it from npm, you can simply import the pieces you need. The examples in this reference all use import syntax.
To get React Router working in your app, you need to render a router element at or near the root of your element tree. We provide several different routers, depending on where you're running your app.
<BrowserRouter>or<HashRouter>should be used when running in a web browser. Which one you pick depends on the style of URL you prefer or need.<StaticRouter>should be used when server-rendering a website<NativeRouter>should be used in React Native apps<MemoryRouter>is useful in testing scenarios and as a reference implementation for the other routers
These routers provide the context that React Router needs to operate in a particular environment. Each one renders a <Router> internally, which you may also do if you need more fine-grained control for some reason. But it is highly likely that one of the built-in routers is what you need.
Routing is the process of deciding which React elements will be rendered on a given page of your app, and how they will be nested. React Router provides two interfaces for declaring your routes.
<Routes>and<Route>if you're using JSXuseRoutesif you'd prefer a JavaScript object-based config
A few low-level pieces that we use internally are also exposed as public API, in case you need to build your own higher-level interfaces for some reason.
matchPath- matches a path pattern against a URL pathnamematchRoutes- matches a set of routes against a locationcreateRoutesFromArray- creates a route config from a set of plain JavaScript objectscreateRoutesFromChildren- creates a route config from a set of React elements (i.e.<Route>elements)
React Router's navigation interfaces let you change the currently rendered page by modifying the current location. There are two main interfaces for navigating between pages in your app, depending on what you need.
<Link>and<NavLink>render an accessible<a>element, or aTouchableHighlighton React Native. This lets the user initiate navigation by clicking or tapping an element on the page.useNavigateand<Navigate>let you programmatically navigate, usually in an event handler or in response to some change in state
There are a few low-level APIs that we use internally that may also prove useful when building your own navigation interfaces.
useResolvedPath- resolves a relative path against the current locationuseHref- resolves a relative path suitable for use as a<a href>useLinkClickHandler- returns an event handler to for navigation when building a custom<Link>inreact-router-domuseLinkPressHandler- returns an event handler to for navigation when building a custom<Link>inreact-router-nativeresolvePath- resolves a relative path against a given URL pathname
Sometimes you need to confirm navigation before it actually happens. For example, if the user has entered some data into a form on the current page, you may want to prompt them to save the data before they navigate to a different page.
usePromptand<Prompt>trigger a platform-native confirmation prompt when the user tries to navigate away from the current pageuseBlockeris a low-level interface that lets you keep the user on the same page and execute a function that will be called when they try to navigate away
Access to the URL search parameters is provided via the useSearchParams hook.
Type declaration
declare function BrowserRouter(props: BrowserRouterProps): React.ReactElement;
interface BrowserRouterProps {
basename?: string;
children?: React.ReactNode;
window?: Window;
}<BrowserRouter> is the recommended interface for running React Router in a web browser. A <BrowserRouter> stores the current location in the browser's address bar using clean URLs and navigates using the browser's built-in history stack.
<BrowserRouter window> defaults to using the current document's defaultView, but it may also be used to track changes to another's window's URL, in an <iframe>, for example.
import React from "react";
import ReactDOM from "react-dom";
import { BrowserRouter } from "react-router-dom";
ReactDOM.render(
<BrowserRouter>{/* The rest of your app goes here */}</BrowserRouter>,
root
);Type declaration
declare function HashRouter(props: HashRouterProps): React.ReactElement;
interface HashRouterProps {
basename?: string;
children?: React.ReactNode;
window?: Window;
}<HashRouter> is for use in web browsers when the URL should not (or cannot) be sent to the server for some reason. This may happen in some shared hosting scenarios where you do not have full control over the server. In these situations, <HashRouter> makes it possible to store the current location in the hash portion of the current URL, so it is never sent to the server.
<HashRouter window> defaults to using the current document's defaultView, but it may also be used to track changes to another window's URL, in an <iframe>, for example.
import React from "react";
import ReactDOM from "react-dom";
import { HashRouter } from "react-router-dom";
ReactDOM.render(
<HashRouter>{/* The rest of your app goes here */}</HashRouter>,
root
);Type declaration
declare function NativeRouter(props: NativeRouterProps): React.ReactElement;
interface NativeRouterProps {
basename?: string;
children?: React.ReactNode;
initialEntries?: InitialEntry[];
initialIndex?: number;
}<NativeRouter> is the recommended interface for running React Router in a React Native app.
<NativeRouter initialEntries>defaults to["/"](a single entry at the root/URL)<NativeRouter initialIndex>defaults to the last index ofprops.initialEntries
import React from "react";
import { NativeRouter } from "react-router-native";
function App() {
return <NativeRouter>{/* The rest of your app goes here */}</NativeRouter>;
}Type declaration
declare function MemoryRouter(props: MemoryRouterProps): React.ReactElement;
interface MemoryRouterProps {
basename?: string;
children?: React.ReactNode;
initialEntries?: InitialEntry[];
initialIndex?: number;
}A <MemoryRouter> stores its locations internally in an array. Unlike <BrowserHistory> and <HashHistory>, it isn't tied to an external source, like the history stack in a browser. This makes it ideal for scenarios where you need complete control over the history stack, like testing.
<MemoryRouter initialEntries>defaults to["/"](a single entry at the root/URL)<MemoryRouter initialIndex>defaults to the last index ofprops.initialEntries
Tip:
Most of React Router's tests are written using a
<MemoryRouter>as the source of truth, so you can see some great examples of using it by just browsing through our tests.
import React from "react";
import { create } from "react-test-renderer";
import { MemoryRouter, Routes, Route } from "react-router-dom";
describe("My app", () => {
it("renders correctly", () => {
let renderer = create(
<MemoryRouter initialEntries={["/users/mjackson"]}>
<Routes>
<Route path="users" element={<Users />}>
<Route path=":id" element={<UserProfile />} />
</Route>
</Routes>
</MemoryRouter>
);
expect(renderer.toJSON()).toMatchSnapshot();
});
});Note:
This is the web version of
<Link>. For the React Native version, go here.
Type declaration
declare function Link(props: LinkProps): React.ReactElement;
interface LinkProps
extends Omit<React.AnchorHTMLAttributes<HTMLAnchorElement>, "href"> {
replace?: boolean;
state?: State;
to: To;
}
type State = object | null;
type To = Partial<Location> | string;A <Link> is an element that lets the user navigate to another page by clicking or tapping on it. In react-router-dom, a <Link> renders an accessible <a> element with a real href that points to the resource it's linking to. This means that things like right-clicking a <Link> work as you'd expect.
import React from "react";
import { Link } from "react-router-dom";
function UsersIndexPage({ users }) {
return (
<div>
<h1>Users</h1>
<ul>
{users.map(user => (
<li key={user.id}>
<Link to={user.id}>{user.name}</Link>
</li>
))}
</ul>
</div>
);
}A relative <Link to> value (that does not begin with /) resolves relative to the parent route, which means that it builds upon the URL path that was matched by the route that rendered that <Link>. It may contain .. to link to routes further up the hierarchy. In these cases, .. works exactly like the command-line cd function; each .. removes one segment of the parent path.
Note:
<Link to>with a..behaves differently from a normal<a href>when the current URL ends with/.<Link to>ignores the trailing slash, and removes one URL segment for each... But an<a href>value handles..differently when the current URL ends with/vs when it does not.
Note:
This is the React Native version of
<Link>. For the web version, go here.
Type declaration
declare function Link(props: LinkProps): React.ReactElement;
interface LinkProps extends TouchableHighlightProps {
onPress?: (event: GestureResponderEvent) => void;
replace?: boolean;
state?: State;
to: To;
}A <Link> is an element that lets the user navigate to another view by tapping it, similar to how <a> elements work in a web app. In react-router-native, a <Link> renders a TouchableHighlight.
import React from "react";
import { View, Text } from "react-native";
import { Link } from "react-router-native";
function Home() {
return (
<View>
<Text>Welcome!</Text>
<Link to="/profile">Visit your profile</Link>
</View>
);
}Type declaration
declare function NavLink(props: NavLinkProps): React.ReactElement;
interface NavLinkProps extends Omit<LinkProps, "className" | "style"> {
caseSensitive?: boolean;
className?: string | ((props: { isActive: boolean }) => string);
end?: boolean;
style?:
| React.CSSProperties
| ((props: { isActive: boolean }) => React.CSSProperties);
}A <NavLink> is a special kind of <Link> that knows whether or not it is "active". This is useful when building a navigation menu such as a breadcrumb or a set of tabs where you'd like to show which of them is currently selected. It also provides useful context for assitive technology like screen readers.
By default, an active class is added to a <NavLink> component when it is active. This provides the same simple styling mechanism for most users who are upgrading from v5. One difference as of v6.0.0-beta.3 is that activeClassName and activeStyle have been removed from NavLinkProps. Instead, you can pass a function to either style or className that will allow you to customize the inline styling or the class string based on the component's active state.
import React from "react";
import { NavLink } from "react-router-dom";
function NavList() {
// This styling will be applied to a <NavLink> when the
// route that it links to is currently selected.
let activeStyle = {
textDecoration: "underline"
};
return (
<nav>
<ul>
<li>
<NavLink
to="messages"
style={({ isActive }) => (isActive ? activeStyle : undefined)}
>
Messages
</NavLink>
</li>
<li>
<NavLink
to="tasks"
style={({ isActive }) => (isActive ? activeStyle : undefined)}
>
Tasks
</NavLink>
</li>
</ul>
</nav>
);
}If you prefer the v5 API, you can create your own <NavLink /> as a wrapper component:
import React from "react";
import { NavLink as BaseNavLink } from "react-router-dom";
const NavLink = React.forwardRef(
({ activeClassName, activeStyle, ...props }, ref) => {
return (
<BaseNavLink
ref={ref}
{...props}
className={({ isActive }) =>
[props.className, isActive ? activeClassName : null]
.filter(Boolean)
.join(" ")
}
style={({ isActive }) => ({
...props.style,
...(isActive ? activeStyle : null)
})}
/>
);
}
);If the end prop is used, it will ensure this component isn't matched as "active" when its descendant paths are matched. For example, to render a link that is only active at the website root and not any other URLs, you can use:
<NavLink to="/" end>
Home
</NavLink>Type declaration
declare function Navigate(props: NavigateProps): null;
interface NavigateProps {
to: To;
replace?: boolean;
state?: State;
}A <Navigate> element changes the current location when it is rendered. It's a component wrapper around useNavigate, and accepts all the same arguments as props.
Note:
Having a component-based version of the
useNavigatehook makes it easier to use this feature in aReact.Componentsubclass where hooks are not able to be used.
import React from "react";
import { Navigate } from "react-router-dom";
class LoginForm extends React.Component {
state = { user: null, error: null };
async handleSubmit(event) {
event.preventDefault();
try {
let user = await login(event.target);
this.setState({ user });
} catch (error) {
this.setState({ error });
}
}
render() {
let { user, error } = this.state;
return (
<div>
{error && <p>{error.message}</p>}
{user && <Navigate to="/dashboard" replace={true} />}
<form onSubmit={event => this.handleSubmit(event)}>
<input type="text" name="username" />
<input type="password" name="password" />
</form>
</div>
);
}
}Type declaration
declare function Outlet(): React.ReactElement | null;An <Outlet> should be used in parent route elements to render their child route elements. This allows nested UI to show up when child routes are rendered. If the parent route matched exactly, it will render nothing.
function Dashboard() {
return (
<div>
<h1>Dashboard</h1>
{/* This element will render either <DashboardMessages> when the URL is
"/messages", <DashboardTasks> at "/tasks", or null if it is "/"
*/}
<Outlet />
</div>
);
}
function App() {
return (
<Routes>
<Route path="/" element={<Dashboard />}>
<Route path="messages" element={<DashboardMessages />} />
<Route path="tasks" element={<DashboardTasks />} />
</Route>
</Routes>
);
}Type declaration
declare function Prompt(props: PromptProps): null;
interface PromptProps {
message: string;
when?: boolean;
}A <Prompt> is the declarative version of usePrompt. It doesn't render anything. It just calls usePrompt with its props.
Note:
Having a component-based version of the
usePrompthook makes it easier to use this feature in aReact.Componentsubclass where hooks are not able to be used.
Type declaration
declare function Router(props: RouterProps): React.ReactElement;
interface RouterProps {
action?: Action;
basename?: string;
children?: React.ReactNode;
location: Location;
navigator: Navigator;
static?: boolean;
}<Router> is the low-level interface that is shared by all router components (<BrowserRouter>, <HashRouter>, <StaticRouter>, <NativeRouter>, and <MemoryRouter>). In terms of React, <Router> is a context provider that supplies routing information to the rest of the app.
You probably never need to render a <Router> manually. Instead, you should use one of the higher-level routers depending on your environment. You only ever need one router in a given app.
The <Router basename> prop may be used to make all routes and links in your app relative to a "base" portion of the URL pathname that they all share. This is useful when rendering only a portion of a larger app with React Router or when your app has multiple entry points. Basenames are not case-sensitive.
Type declaration
declare function Routes(props: RoutesProps): React.ReactElement | null;
interface RoutesProps {
children?: React.ReactNode;
location?: Partial<Location> | string;
}
declare function Route(props: RouteProps): React.ReactElement | null;
interface RouteProps {
caseSensitive?: boolean;
children?: React.ReactNode;
element?: React.ReactElement | null;
index?: boolean;
path?: string;
}<Routes> and <Route> are the primary ways to render something in React Router based on the current location. You can think about a <Route> kind of like an if statement; if its path matches the current URL, it renders its element! The <Route caseSensitive> prop determines if the matching should be done in a case-sensitive manner (defaults to false).
Whenever the location changes, <Routes> looks through all its children <Route> elements to find the best match and renders that branch of the UI. <Route> elements may be nested to indicate nested UI, which also correspond to nested URL paths. Parent routes render their child routes by rendering an <Outlet>.
<Routes>
<Route path="/" element={<Dashboard />}>
<Route path="messages" element={<DashboardMessages />} />
<Route path="tasks" element={<DashboardTasks />} />
</Route>
<Route path="about" element={<AboutPage />} />
</Routes>Note:
If you'd prefer to define your routes as regular JavaScript objects instead of using JSX, try
useRoutesinstead.
The default <Route element> is an <Outlet>. This means the route will still render its children even without an explicit element prop, so you can nest route paths without nesting UI around the child route elements.
For example, in the following config the parent route renders an <Outlet> by default, so the child route will render without any surrounding UI. But the child route's path is /users/:id because it still builds on its parent.
<Route path="users">
<Route path=":id" element={<UserProfile />} />
</Route>Type declaration
declare function StaticRouter(props: StaticRouterProps): React.ReactElement;
interface StaticRouterProps {
basename?: string;
children?: React.ReactNode;
location?: Path | LocationPieces;
}<StaticRouter> is used to render a React Router web app in node. Provide the current location via the location prop.
<StaticRouter location>defaults to"/"
import React from "react";
import ReactDOMServer from "react-dom/server";
import { StaticRouter } from "react-router-dom/server";
import http from "http";
function requestHandler(req, res) {
let html = ReactDOMServer.renderToString(
<StaticRouter location={req.url}>
{/* The rest of your app goes here */}
</StaticRouter>
);
res.write(html);
res.end();
}
http.createServer(requestHandler).listen(3000);Type declaration
declare function createRoutesFromChildren(
children: React.ReactNode
): RouteObject[];
interface RouteObject {
caseSensitive?: boolean;
children?: RouteObject[];
element?: React.ReactNode;
index?: boolean;
path?: string;
}createRoutesFromChildren is a helper that creates route objects from <Route> elements. It is used internally in a <Routes> element to generate a route config from its <Route> children.
Type declaration
declare function generatePath(path: string, params?: Params): string;generatePath interpolates a set of params into a route path string with :id and * placeholders. This can be useful when you want to eliminate placeholders from a route path so it matches statically instead of using a dynamic parameter.
generatePath("/users/:id", { id: 42 }); // "/users/42"
generatePath("/files/:type/*", { type: "img", "*": "cat.jpg" }); // "/files/img/cat.jpg"The term "location" in React Router refers to the Location interface from the history library.
Note:
The history package is React Router's main dependency and many of the core types in React Router come directly from that library including
Location,To,Path,State, and others. You can read more about the history library in its documentation.
Type declaration
declare function matchRoutes(
routes: RouteObject[],
location: Partial<Location> | string
): RouteMatch[] | null;
interface RouteMatch {
params: Params;
pathname: string;
route: RouteObject;
}matchRoutes runs the route matching algorithm for a set of routes against a given location to see which routes (if any) match. If it finds a match, an array of RouteMatch objects is returned, one for each route that matched.
This is the heart of React Router's matching algorithm. It is used internally by useRoutes and the <Routes> component to determine which routes match the current location. It can also be useful in some situations where you want to manually match a set of routes.
Type declaration
declare function matchPath<ParamKey extends string = string>(
pattern: PathPattern,
pathname: string
): PathMatch<ParamKey> | null;
interface PathMatch {
params: Params;
pathname: string;
pattern: PathPattern;
}
type PathPattern =
| { path: string; caseSensitive?: boolean; end?: boolean }
| string;matchPath matches a route path pattern against a URL pathname and returns information about the match. This is useful whenever you need to manually run the router's matching algorithm to determine if a route path matches or not. It returns null if the pattern does not match the given pathname.
The useMatch hook uses this function internally to match a route path relative to the current location.
Type declaration
declare function resolvePath(to: To, fromPathname = "/"): Path;
type To = Partial<Location> | string;
interface Path {
pathname: string;
search: string;
hash: string;
}resolvePath resolves a given To value into an actual Path object with an absolute pathname. This is useful whenever you need to know the exact path for a relative To value. For example, the <Link> component uses this function to know the actual URL it points to.
The useResolvedPath hook uses resolvePath internally to resolve the pathname. If to contains a pathname, it is resolved against the current route pathname. Otherwise, it is resolved against the current URL (location.pathname).
Type declaration
declare function useBlocker(blocker: Blocker, when = true): void;useBlocker is a low-level hook that allows you to block navigation away from the current page, i.e. prevent the current location from changing. This is probably something you don't ever want to do unless you also display a confirmation dialog to the user to help them understand why their navigation attempt was blocked. In these cases, you probably want to use usePrompt or <Prompt> instead.
Type declaration
declare function useHref(to: To): string;The useHref hook returns a URL that may be used to link to the given to location, even outside of React Router.
Tip:
You may be interested in taking a look at the source for the
<Link>component inreact-router-domto see how it usesuseHrefinternally to determine its ownhrefvalue.
Type declaration
declare function useLinkClickHandler<
E extends Element = HTMLAnchorElement,
S extends State = State
>(
to: To,
options?: {
target?: React.HTMLAttributeAnchorTarget;
replace?: boolean;
state?: S;
}
): (event: React.MouseEvent<E, MouseEvent>) => void;The useLinkClickHandler hook returns a click event handler to for navigation when building a custom <Link> in react-router-dom.
import { useHref, useLinkClickHandler } from "react-router-dom";
const StyledLink = styled("a", { color: "fuschia" });
const Link = React.forwardRef(
({ onClick, replace = false, state, target, to, ...rest }, ref) => {
let href = useHref(to);
let handleClick = useLinkClickHandler(to, { replace, state, target });
return (
<StyledLink
{...rest}
href={href}
onClick={event => {
onClick?.(event);
if (!event.defaultPrevented) {
handleClick(event);
}
}}
ref={ref}
target={target}
/>
);
}
);Type declaration
declare function useLinkPressHandler<S extends State = State>(
to: To,
options?: {
replace?: boolean;
state?: S;
}
): (event: GestureResponderEvent) => void;The react-router-native counterpart to useLinkClickHandler, useLinkPressHandler returns a press event handler for custom <Link> navigation.
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 (
<TouchableHighlight
{...rest}
onPress={event => {
onPress?.(event);
if (!event.defaultPrevented) {
handlePress(event);
}
}}
/>
);
}Type declaration
declare function useInRouterContext(): boolean;The useInRouterContext hooks returns true if the component is being rendered in the context of a <Router>, false otherwise. This can be useful for some 3rd-party extensions that need to know if they are being rendered in the context of a React Router app.
Type declaration
declare function useLocation(): Location;This hook returns the current location object. This can be useful if you'd like to perform some side effect whenever the current location changes.
import React from 'react';
import { useLocation } from 'react-router-dom';
function App() {
let location = useLocation();
React.useEffect(() => {
ga('send', 'pageview');
}, [location]);
return (
// ...
);
}Type declaration
declare function useMatch<ParamKey extends string = string>(
pattern: PathPattern | string
): PathMatch<ParamKey> | null;Returns match data about a route at the given path relative to the current location.
See matchPath for more information.
Type declaration
declare function useNavigate(): NavigateFunction;
interface NavigateFunction {
(to: To, options?: { replace?: boolean; state?: State }): void;
(delta: number): void;
}The useNavigate hook returns a function that lets you navigate programmatically, for example after a form is submitted.
import { useNavigate } from "react-router-dom";
function SignupForm() {
let navigate = useNavigate();
async function handleSubmit(event) {
event.preventDefault();
await submitForm(event.target);
navigate("../success", { replace: true });
}
return <form onSubmit={handleSubmit}>{/* ... */}</form>;
}The navigate function has two signatures:
- Either pass a
Tovalue (same type as<Link to>) with an optional second{ replace, state }arg or - Pass the delta you want to go in the history stack. For example,
navigate(-1)is equivalent to hitting the back button.
Type declaration
declare function useOutlet(): React.ReactElement | null;Returns the element for the child route at this level of the route hierarchy. This hook is used internally by <Outlet> to render child routes.
Type declaration
declare function useParams<Key extends string = string>(): Params<Key>;The useParams hook returns an object of key/value pairs of the dynamic params from the current URL that were matched by the <Route path>. Child routes inherit all params from their parent routes.
import React from 'react';
import { Routes, Route, useParams } from 'react-router-dom';
function ProfilePage() {
// Get the userId param from the URL.
let { userId } = useParams();
// ...
}
function App() {
return (
<Routes>
<Route path="users">
<Route path=":userId" element={<ProfilePage />} />
<Route path="me" element={...} />
</Route>
</Routes>
);
}Type declaration
declare function usePrompt(message: string, when = true): void;The usePrompt hook may be used to confirm navigation before the user navigates away from the current page. This is useful when someone has entered unsaved data into a form, and you'd like to prompt them before they accidentally leave or close the tab and lose their work.
import React from "react";
import { usePrompt } from "react-router-dom";
function SignupForm() {
let [formData, setFormData] = React.useState(null);
usePrompt("Are you sure you want to leave?", formData != null);
// ...
}usePrompt uses window.confirm on the web and the Alert module on React Native to display native, accessible confirm dialogs.
Note:
If you need a more custom dialog box, you will have to use
useBlockerdirectly and handle accessibility issues yourself.
Type declaration
declare function useResolvedPath(to: To): Path;This hook resolves the pathname of the location in the given to value against the pathname of the current location.
This is useful when building links from relative values. For example, check out the source to <NavLink> which calls useResolvedPath internally to resolve the full pathname of the page being linked to.
See resolvePath for more information.
Type declaration
declare function useRoutes(
routes: RouteObject[],
location?: Partial<Location> | string;
): React.ReactElement | null;The useRoutes hook is the functional equivalent of <Routes>, but it uses JavaScript objects instead of <Route> elements to define your routes. These objects have the same properties as normal <Route> elements, but they don't require JSX.
The return value of useRoutes is either a valid React element you can use to render the route tree, or null if nothing matched.
import React from "react";
import { useRoutes } from "react-router-dom";
function App() {
let element = useRoutes([
{
path: "/",
element: <Dashboard />,
children: [
{ path: "messages", element: <DashboardMessages /> },
{ path: "tasks", element: <DashboardTasks /> }
]
},
{ path: "team", element: <AboutPage /> }
]);
return element;
}See also createRoutesFromArray.
Type declaration
declare function useSearchParams(
defaultInit?: URLSearchParamsInit
): [
URLSearchParams,
(
nextInit: URLSearchParamsInit,
navigateOptions?: { replace?: boolean; state?: State }
) => void
];
type ParamKeyValuePair = [string, string];
type URLSearchParamsInit =
| string
| ParamKeyValuePair[]
| Record<string, string | string[]>
| URLSearchParams;The useSearchParams hook is used to read and modify the query string in the URL for the current location. Like React's own useState hook, useSearchParams returns an array of two values: the current location's search params and a function that may be used to update them.
import 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 (
<div>
<form onSubmit={handleSubmit}>{/* ... */}</form>
</div>
);
}Note:
The
setSearchParamsfunction works likenavigate, but only for the search portion of the URL. Also note that the second arg tosetSearchParamsis the same type as the second arg tonavigate.
A createSearchParams(init: URLSearchParamsInit) function is also exported that is essentially a thin wrapper around new URLSearchParams(init) that adds support for using objects with array values. This is the same function that useSearchParams uses internally for creating URLSearchParams objects from URLSearchParamsInit values.