3

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 2

6

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} />
Sign up to request clarification or add additional context in comments.

Comments

2

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).

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.