Skip to content

API Reference

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.

Overview

Packages

React Router is published to npm in three different packages:

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 import the pieces you need. The examples in this reference all use import syntax.

Setup

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 your app is running.

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

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.

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.

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 a TouchableHighlight on React Native. This lets the user initiate navigation by clicking or tapping an element on the page.
  • useNavigate and <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.

Search Parameters

Access to the URL search parameters is provided via the useSearchParams hook.


Reference

<BrowserRouter>

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 * as React from "react";
import * as ReactDOM from "react-dom";
import { BrowserRouter } from "react-router-dom";

ReactDOM.render(
  <BrowserRouter>
    {/* The rest of your app goes here */}
  </BrowserRouter>,
  root
);

<HashRouter>

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 * as React from "react";
import * as ReactDOM from "react-dom";
import { HashRouter } from "react-router-dom";

ReactDOM.render(
  <HashRouter>
    {/* The rest of your app goes here */}
  </HashRouter>,
  root
);

We strongly recommend you do not use HashRouter unless you absolutely have to.

<NativeRouter>

Type declaration
declare function NativeRouter(
  props: NativeRouterProps
): React.ReactElement;

interface NativeRouterProps extends MemoryRouterProps {}

<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 of initialEntries
import * as React from "react";
import { NativeRouter } from "react-router-native";

function App() {
  return (
    <NativeRouter>
      {/* The rest of your app goes here */}
    </NativeRouter>
  );
}

<MemoryRouter>

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 of 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 * as 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?: any;
  to: To;
  reloadDocument?: boolean;
}

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. You can use <Link reloadDocument> to skip client side routing and let the browser handle the transition normally (as if it were an <a href>).

import * as 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 {
  children?: React.ReactNode;
  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. To override default styling and behaviour, please refer to the Props reference for TouchableHighlight.

import * as 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 assistive 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 * as 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 * as 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 useNavigate hook makes it easier to use this feature in a React.Component subclass where hooks are not able to be used.

import * as 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>
    );
  }
}

<Outlet>

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 a child index route or nothing if there is no index route.

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>
  );
}

<Router>

Type declaration
declare function Router(
  props: RouterProps
): React.ReactElement | null;

interface RouterProps {
  basename?: string;
  children?: React.ReactNode;
  location: Partial<Location> | string;
  navigationType?: NavigationType;
  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.

<Routes> and <Route>

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 useRoutes instead.

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>

<StaticRouter>

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 * as React from "react";
import * as 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);

createRoutesFromArray

Type declaration
declare function createRoutesFromArray(
  array: PartialRouteObject[]
): RouteObject[];

interface PartialRouteObject {
  path?: string;
  caseSensitive?: boolean;
  element?: React.ReactNode;
  children?: PartialRouteObject[];
}

interface RouteObject {
  caseSensitive: boolean;
  children?: RouteObject[];
  element: React.ReactNode;
  path: string;
}

createRoutesFromArray is a helper that fills in the (potentially) missing pieces in an array of route objects. It is used internally by useRoutes to create route objects.

createRoutesFromChildren

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.

generatePath

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"

Location

The term "location" in React Router refers to the Location interface from the history library.

Note:

The history package is React Router's only 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.

matchRoutes

Type declaration
declare function matchRoutes(
  routes: RouteObject[],
  location: Partial<Location> | string,
  basename?: string
): RouteMatch[] | null;

interface RouteMatch<ParamKey extends string = string> {
  params: Params<ParamKey>;
  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.

renderMatches

Type declaration
declare function renderMatches(
  matches: RouteMatch[] | null
): React.ReactElement | null;

renderMatches renders the result of matchRoutes() into a React element.

matchPath

Type declaration
declare function matchPath<
  ParamKey extends string = string
>(
  pattern: PathPattern | string,
  pathname: string
): PathMatch<ParamKey> | null;

interface PathMatch<ParamKey extends string = string> {
  params: Params<ParamKey>;
  pathname: string;
  pattern: PathPattern;
}

interface PathPattern {
  path: string;
  caseSensitive?: boolean;
  end?: boolean;
}

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.

resolvePath

Type declaration
declare function resolvePath(
  to: To,
  fromPathname?: string
): 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).

useHref

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 in react-router-dom to see how it uses useHref internally to determine its own href value.

useLinkClickHandler

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: "fuchsia" });

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}
      />
    );
  }
);

useLinkPressHandler

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);
        }
      }}
    />
  );
}

useInRouterContext

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.

useLocation

Type declaration
declare function useLocation(): Location;

interface Location<S extends State = object | null>
  extends Path {
  state: S;
  key: Key;
}

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 * as React from 'react';
import { useLocation } from 'react-router-dom';

function App() {
  let location = useLocation();

  React.useEffect(() => {
    ga('send', 'pageview');
  }, [location]);

  return (
    // ...
  );
}

useNavigationType

Type declaration
declare function useNavigationType(): NavigationType;

type NavigationType = "POP" | "PUSH" | "REPLACE";

This hook returns the current type of navigation or how the user came to the current page; either via a pop, push, or replace action on the history stack.

useMatch

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.

useNavigate

Type declaration
declare function useNavigate(): NavigateFunction;

interface NavigateFunction {
  (
    to: To,
    options?: { replace?: boolean; state?: any }
  ): 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 To value (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.

useOutlet

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.

useParams

Type declaration
declare function useParams<
  K extends string = string
>(): Readonly<Params<K>>;

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 * as 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>
  );
}

useResolvedPath

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.

useRoutes

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 * as 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.

useSearchParams

Note:

This is the web version of useSearchParams. For the React Native version, go here.

Type declaration
declare function useSearchParams(
  defaultInit?: URLSearchParamsInit
): [URLSearchParams, URLSearchParamsSetter];

type ParamKeyValuePair = [string, string];

type URLSearchParamsInit =
  | string
  | ParamKeyValuePair[]
  | Record<string, string | string[]>
  | URLSearchParams;

interface URLSearchParamsSetter {
  (
    nextInit: URLSearchParamsInit,
    navigateOptions?: { replace?: boolean; state?: State }
  ): void;
}

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 * 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 (
    <div>
      <form onSubmit={handleSubmit}>{/* ... */}</form>
    </div>
  );
}

Note:

The setSearchParams function works like navigate, but only for the search portion of the URL. Also note that the second arg to setSearchParams is the same type as the second arg to navigate.

useSearchParams (React Native)

Note:

This is the React Native version of useSearchParams. For the web version, go here.

Type declaration
declare function useSearchParams(
  defaultInit?: URLSearchParamsInit
): [URLSearchParams, URLSearchParamsSetter];

type ParamKeyValuePair = [string, string];

type URLSearchParamsInit =
  | string
  | ParamKeyValuePair[]
  | Record<string, string | string[]>
  | URLSearchParams;

interface URLSearchParamsSetter {
  (
    nextInit: URLSearchParamsInit,
    navigateOptions?: { replace?: boolean; state?: State }
  ): void;
}

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 * as React from "react";
import { View, SearchForm, TextInput } from "react-native";
import { useSearchParams } from "react-router-native";

function App() {
  let [searchParams, setSearchParams] = useSearchParams();
  let [query, setQuery] = React.useState(
    searchParams.get("query")
  );

  function handleSubmit() {
    setSearchParams({ query });
  }

  return (
    <View>
      <SearchForm onSubmit={handleSubmit}>
        <TextInput value={query} onChangeText={setQuery} />
      </SearchForm>
    </View>
  );
}

createSearchParams

Type declaration
declare function createSearchParams(
  init?: URLSearchParamsInit
): URLSearchParams;

createSearchParams is 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.