How set a default queryString parameter in every path in React?

Viewed 39

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 Answers

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

Related