1

I need to add a parameter in each route of my application, this parameter should stay in the route when I use the redirect, how do I do this?

The way that works is add manually the param in every path, something like this:

const useCustomParams = (): { customParam: string }=> {
  const { search } = useLocation()

  const urlParams = useMemo(() => new URLSearchParams(search), [search])
  const customParam = `?org=${urlParams.get('org') ?? ''}`

  return { customParam }
}

...

const { customParam } = useCustomParams()

...

<Route
    path="*"
    element={<Navigate to={`/group/${id}/users${customParam}`} replace />}
/>

... or

navigate({`/group/${id}/users${customParam}`})

1 Answer 1

2

I think it would just be easier to use the useSearchParams hook in the rendered component and provide a fallback "" value if the ord queryString parameter is falsey, but if you are looking for a more DRY method of doing this then I suggest creating a layout route component that handles "injecting" an org queryString parameter for a specific set of routes.

Example:

import { useEffect } from 'react';
import { Outlet, useSearchParams } from 'react-router-dom';

const OrgParamRoutes = () => {
  const [searchParams, setSearchParams] = useSearchParams();

  useEffect(() => {
    if (searchParams.get("org") === null) {
      searchParams.set("org", "");
      setSearchParams(searchParams);
    }
  }, [searchParams, setSearchParams]);

  return <Outlet />;
};

Usage:

<Routes>
  <Route path="/" element={<div>Home</div>} />
  ... other routes that will not get org queryString param injected ...
  <Route element={<OrgParamRoutes />}>
    <Route path="/org" element={<div>Org</div>} />
    ... other routes that will get org queryString param injected ...
  </Route>
</Routes>

Edit how-set-a-default-parameter-in-every-paths-in-react

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.