chingis
chingis

Reputation: 1790

How to redirect with match params in React Router v6?

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 />} />

Upvotes: 6

Views: 4431

Answers (3)

Andreas Riedm&#252;ller
Andreas Riedm&#252;ller

Reputation: 1489

I am using this helper Component to pass params to Navigate:

function NavigateWithParams({ to, ...rest }) {
  const params = useParams();
  let toValue;
  if (typeof to === 'function') {
    toValue = to(params);
  } else {
    toValue = to;
  }
  return <Navigate to={toValue} {...rest} />
}

Usage:

<Route
  path="/test/:id/results"
  element={<NavigateWithParams 
    to={params => `/test/${params.id}/report`} 
    replace
  />}
/>

Upvotes: 3

Drew Reese
Drew Reese

Reputation: 203587

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

Upvotes: 4

chingis
chingis

Reputation: 1790

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 />} />

Upvotes: 4

Related Questions