Overlapping routes in react-router

Viewed 350

I've got number of nested routes and would want them to be displayed one at time.

The top route is, let's say, '/sports'

<>
  <Route exact path={`${match.path}/favs`} component={LiveFavs} />
  <Route exact path={`${match.path}/:sportId`} render={props => <Live {...props.match.params} />} />
  <Route exact path={`${match.path}/:sportId/:eventId`} render={props => <LiveEvent {...props.match.params} />} />
</>

Navigating to /sports/favs should display first route ONLY, but currently it's mixed with route no. 2 (:sportId)

1 Answers

You need to import the Switch component from react-router-dom and wrap it around your Routes. Essentially, it goes through your routes and renders only the first route who's path is satisfied by the URL being navigated to.

Try this:

<Switch>
  <Route exact path={`${match.path}/favs`} component={LiveFavs} />
  <Route exact path={`${match.path}/:sportId`} render={props => <Live {...props.match.params} />} />
  <Route exact path={`${match.path}/:sportId/:eventId`} render={props => <LiveEvent {...props.match.params} />} />
</Switch>
Related