user0101
user0101

Reputation: 1517

Overlapping routes in react-router

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)

Upvotes: 2

Views: 752

Answers (1)

Cat_Enthusiast
Cat_Enthusiast

Reputation: 15688

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>

Upvotes: 3

Related Questions