How to redirect with match params in React Router v6?

Viewed 1505

I used to do this in react router v5:

<Redirect exact from="/:org" to="/:org/users" />

translating it into this doesn't work:

<Route path="/:org" element={<Navigate replace to="/:org/users" />} />

What is the correct way to perform this kind of a redirect?

UPD: To clarify – I don't have a separate route for /:org/users at the same routes level but I have /:org/* route that handles /:org/users and others:

<Route path="/:org/*" element={<OrgPagesComponent />} />
2 Answers

so far I've come up with the following solution:

const OrgRedirect = () => {
  const { org } = useParams();
  return <Navigate to={`/${org}/users`} />
}

<Route path="/:org" element={<OrgRedirect />} />

Use relative navigation for the redirect.

<Route path="/:org/*" element={<OrgPagesComponent />} />
<Route path="/:org" element={<Navigate to="users" replace />} />

When the path matches exactly "/:org" the second Route will be matched and render the Navigate which will relatively navigate to "/:org/users" which is matched by the first Route on path "/:org/*".

Here is a running codesandbox demo.

Edit how-to-redirect-with-match-params-in-react-router-v6

Related