React-router: match path with optional params (v4)

Created on 23 Feb 2017  路  3Comments  路  Source: ReactTraining/react-router

Hey guys:
Can i match all routes with a path like this:

/work/:workId(/:stepName)(/:goodId/:stepName)

I expect to catch all the routes with the following paths:

/work/work_id_12/step1
/work/work_id_12/good_id_11/step1

Most helpful comment

v4 uses path-to-regexp. You can check its documentation on how to format params. This is different than in previous versions of React Router.

Personally instead of trying to overload the path, I would write this something like:

<Route path='/work/:workId' component={WorkRoutes} />

const WorkRoutes = ({ match }) => (
  <Switch>
    <Route exact path={`${match.url}`} component={Work} />
    <Route path={`${match.url}/:goodId/:stepName`} component={Step} />
    <Route path={`${match.url}/:stepName`} component={Step} />
  </Switch>
)

You can test out route configuration using this route tester

All 3 comments

the optional params doesn't seem to work

v4 uses path-to-regexp. You can check its documentation on how to format params. This is different than in previous versions of React Router.

Personally instead of trying to overload the path, I would write this something like:

<Route path='/work/:workId' component={WorkRoutes} />

const WorkRoutes = ({ match }) => (
  <Switch>
    <Route exact path={`${match.url}`} component={Work} />
    <Route path={`${match.url}/:goodId/:stepName`} component={Step} />
    <Route path={`${match.url}/:stepName`} component={Step} />
  </Switch>
)

You can test out route configuration using this route tester

thanks man this is really usefull :)

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Waquo picture Waquo  路  3Comments

ryansobol picture ryansobol  路  3Comments

sarbbottam picture sarbbottam  路  3Comments

maier-stefan picture maier-stefan  路  3Comments

ackvf picture ackvf  路  3Comments