Reputation: 1790
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
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
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.
Upvotes: 4
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