How to use both state and query params with useNavigate in React Router

Viewed 28

React Router 6.3.0

Is there a way to be able to pass state and query params in same navigate call, and have both applied?

Steps to Reproduce

  1. Try

    navigate(
      { 
        pathname: "/search",
        search: `?${createSearchParams({ query: someQuery })}`,
        state: { someAttributeName: someAttributeValue }
      }
    );
    

Note that the query params are passed in the URL but state will be null.

  1. Try

    navigate(
      "/search",
      {
        search: `?${createSearchParams({query: someQuery})}`,
        state: { someAttributeName: someAttributeValue }
      }
    );
    

Note that the state is passed but the query params are not applied.

1 Answers

The search value can be sent in the To object in the first argument, and the state as a property in the options object in the second argument.

useNavigate

declare function useNavigate(): NavigateFunction;

interface NavigateFunction {
  (
    to: To,
    options?: {
      replace?: boolean;
      state?: any;
      relative?: RelativeRoutingType;
    }
  ): void;
  (delta: number): void;
}

To type

export type To = string | Partial<Path>;

Partial<Path> type

/**
 * The pathname, search, and hash values of a URL.
 */
export interface Path {
  /**
   * A URL pathname, beginning with a /.
   *
   * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#location.pathname
   */
  pathname: Pathname;

  /**
   * A URL search string, beginning with a ?.
   *
   * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#location.search
   */
  search: Search;

  /**
   * A URL fragment identifier, beginning with a #.
   *
   * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#location.hash
   */
  hash: Hash;
}

Your code:

navigate(
  { 
    pathname: "/search",
    search: `?${createSearchParams({ query: someQuery })}`,
  },
  { state: { someAttributeName: someAttributeValue } },
);
Related