react-router 6 Navigate to using params

Viewed 1575

In v5 i have such structure

{
    path: '/someurl/:id',
    exact: true,
    render: ({ params }) => (<Redirect to={`/someurl/extraurl/${params.id}`} />),
}

How to refactor this to V6?

2 Answers

react-router-dom v6 no longer has route props, so you'll need to create a new component to gather the "props", or match.params in this case, and render the redirect as a Navigate component.

const MyRedirect = () => {
  const { id } = useParams();
  return <Navigate to={`/someurl/extraurl/${id}`} replace />;
};

...

{
  path: '/someurl/:id',
  element: <MyRedirect />,
}

...

<Route path={obj.path} element={obj.element} />

The accepted answer will work but I'll add my solution too, since it's a bit more dynamic. You can set up a function component that will make use of the useParams hook and the generatePath function so your intended destination gets the params from the initial route (whatever they may be):

import React, { FunctionComponent } from 'react';
import { generatePath, Navigate, useParams } from 'react-router-dom';

interface IProps {
    to: string;
    replace?: boolean;
    state?: any;
}

const Redirect: FunctionComponent<IProps> = ({ to, replace, state }) => {
    const params = useParams();
    const redirectWithParams = generatePath(to, params);

    return (
        <Navigate to={redirectWithParams} replace={replace} state={state} />
    );
};

export default Redirect;

Using this should work with your first example (and any other routes / redirects with dynamic params).

Related