4.2.0
https://codesandbox.io/s/p51on3mxlx
Something like this
<Redirect from="/topics/:id" to="/topic/:id" />
Redirect from like /topics/1 to /topic/1 as it is described in official docs: https://reacttraining.com/react-router/web/api/Redirect/from-string
Ignoring matched params and redirecting from /topics/1 to /topic/:id
Looks like there is same problem https://stackoverflow.com/questions/43399740/react-router-redirect-drops-param
This isn't released yet. But soon!
Why is it in the doc so? https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/Redirect.md#from-string
I needed it 4 months ago and also needed it today, it's still not released :(
In the meantime:
<Route
exact
path="/foo-:id/"
render={props => (
<Redirect to={`/foo-${props.match.params.id}/bar/`} />
)}
/>
Wow. This feature being in the docs, but not supported, has lost me hours this morning
In any case, here is a generic component to use in the meanwhile:
import pathToRegexp from "path-to-regexp";
import { Route, Redirect } from "react-router";
// generatePath is planned for next RR release, so we implement here temporarily
const cache = {};
const generatePath = (path, params) => {
if(!cache[path]) {
cache[path] = pathToRegexp.compile(path);
}
return cache[path](params);
}
const RedirectRoute = ({ to, from }) => {
const render = props => (
<Redirect to={generatePath(to, props.match.params)} />
);
return <Route exact path={from} render={render} />;
};
export default RedirectRoute;
Usage:
<Switch>
<RedirectRoute from="/topics/:id" to="/topic/:id" />
<Route path="/topic/:id" component={Foo} />
</Switch>
@timdorr i beg you to update the docs and add some workarounds till this feature release.
It's like a false beacon, lots of developers doesn't even know what they do wrong.
I'll be putting out a release very soon.
Most helpful comment
I'll be putting out a release very soon.