React router v4 - How to combine dynamic and optional routes?

I need a 2 level routing at root level where the both routes are dynamic and second route is optional. I tried to set up my path as below but got an error.

Here is my route configuration:

<Switch>
  <Route exact path='/' component={CompOne} />
  <Route path='/:name/:id?'
      render={(routeProps) => (
          <Details {...routeProps} />
      )}
  />
</Switch>

Here I have name as one dynamic params, id is the second but its optional.

In browser when I load: localhost:8080/vishal or localhost:8080/vishal/123, it should load the same component. Inside component I check if the url has the id. However, I get 404 error:

https://localhost:8080/vishal/123/bootstrap.min.css

https://localhost:8080/vishal/123/bundle.js

If I wrap optional param in (), I get below error: <Switch> <Route exact path='/' component={CompOne} /> <Route path='/:name(/:id)?' render={(routeProps) => ( <Details {...routeProps} /> )} /> </Switch>

I get 404 that bundle.js not found in case I pass in id as well. hence /vishal works, /vishal/123 gives error 404 - localhost:8080/vishal/bundle.js.

1 answer

  • answered 2018-04-17 04:54 AJ Genung

    try this...

        <Switch>
          <Route exact path='/' component={CompOne} />
          <Route path='/:name/:id?'
              render={(routeProps) => {
                  console.log(routeProps);
                  return <Details {...routeProps} />;
              }}
          />
        </Switch>