skip to Main Content

Currently I have

createBrowserRouter(
  createRoutesFromElements(...)
);

and nested within there is a:

<Route index element={<Navigate to="/raters/start/" />} />

This works fine for the base URL, except that we now need to capture any query strings on the original route and pass those on when we re-route the browser.

Is there something like this functionality available?

<Route
  index
  path="?:queryString"
  element={<Navigate to={`/raters/start?${queryString}`} />}
/>

2

Answers


  1. Chosen as BEST ANSWER

    Another approach is to use a loader to redirect:

    const redirectToRaterStart = async ({ params, request }) => {
      const [, searchParams] = request.url.split("?");
      const policyId = params.policy_id;
      return redirect(
        `/raters/start${policyId ? `/${policyId}` : ""}${
          searchParams ? `?${searchParams}` : ""
        }`
      );
    };
    
    <Route index loader={redirectToRaterStart} />
    <Route path=":policy_id" loader={redirectToRaterStart} />
    

  2. The URL search string is not used for route path matching, it is invalid to include it in the path prop string. You’ll need to manually capture and forward the URL path + searchParams.

    Examples:

    • Custom component

      import { Navigate, useSearchParams } from "react-router-dom";
      
      const NavigateWithSearchParams = (props) => {
        const [searchParams] = useSearchParams();
      
        const newProps = {
          ...props,
          to: {
            // Don't spread `to` prop when it is a string value
            ...(typeof props.to === "string" ? { pathname: props.to } : props.to),
            search: searchParams.toString(),
          },
        };
      
        return <Navigate {...newProps} />;
      };
      
      <Route
        index
        element={<NavigateWithSearchParams to="/raters/start" />}
      />
      
    • Read and forward window.location.search

      <Route
        index
        element={
          <Navigate
            to={{
              pathname: "/raters/start",
              search: window.location.search,
            }}
          />
        }
      />
      
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search