I'm using createBrowserRouter
to define routing in my app. I would also like to define some redirect/rewrite routes like:
/original => /redirected/location
and I'm able to define these quite simply by
{
path: '/original',
element: <Navigate replace to="/redirected/location" />
}
The problem I'm having is when I would like to redirect a route with path parameter:
/original/:paramName => /redirected/location/:paramName
How do I handle these in the declarative way to extract and remap the same variable value to the new URL?
Note: I've created my own component to accomplish this, but I suspect this should be solvable with out of the box functionality without resorting to custom components.
interface Props {
paramName: string;
to: (value: string) => string;
}
export const NavigateWithParam: FunctionComponent<Props> = ({ paramName, to }) => {
const paramValue = useParams()[paramName];
return <Navigate replace to={to(paramValue ?? '')} />;
};
You are close. You will have to create a custom "Navigate" component that can read the current path params, and pass, i.e. forward, those to the new path via the generatPath
utility function. Note that the params that should be forwarded should maintain the same path param name in the new path.
import { Navigate, NavigateProps, generatePath } from 'react-router-dom';
export const NavigateWithParams = ({ to, ...props }: NavigateProps) => {
const params = useParams();
return <Navigate {...props} to={generatePath(to, params)} />;
};
{
path: "/original/:paramName",
element: <NavigateWithParams replace to="/redirected/location/:paramName" />
}