React-router: Redirect with matched parameters doesn't work

Created on 1 Mar 2018  路  8Comments  路  Source: ReactTraining/react-router

Version

4.2.0

Test Case

https://codesandbox.io/s/p51on3mxlx

Steps to reproduce

Something like this
<Redirect from="/topics/:id" to="/topic/:id" />

Expected Behavior

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

Actual Behavior

Ignoring matched params and redirecting from /topics/1 to /topic/:id

Most helpful comment

I'll be putting out a release very soon.

All 8 comments

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.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

ArthurRougier picture ArthurRougier  路  3Comments

winkler1 picture winkler1  路  3Comments

tomatau picture tomatau  路  3Comments

wzup picture wzup  路  3Comments

andrewpillar picture andrewpillar  路  3Comments