Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Router: Route with nested params not hit

In my react app, I have set up routes like this

class App extends Component {
  render() {
    return (
      <div className="app">
        <Header />
        <Route exact path="/" component={PostList} />
        <Route exact path="/:category" component={PostList} />
        <Route exact path="/:category/:postid" component={PostDetails} />
      </div>
    );
  }
}

/ and foo are rendering the PostList component just fine. But when I try to reach the PostDetails component with for instance /foo/bar, it does not get hit.

I tried to play around with the order of the route definitions as well as with the exact prop, but no luck. Not getting any errors, the inspector in devtools just does not show any output where the component should be at.

What am I missing here? I am using [email protected].

like image 435
Hinrich Avatar asked Dec 19 '25 04:12

Hinrich


1 Answers

If you want only one of the routes to show, you should use a Switch.

class App extends Component {
  render() {
    return (
      <div className="app">
        <Header />
        <Switch>
            <Route exact path="/" component={PostList} />
            <Route exact path="/:category" component={PostList} />
            <Route exact path="/:category/:postid" component={PostDetails} />
        </Switch>
      </div>
    );
  }
}
like image 145
ChrisR Avatar answered Dec 21 '25 20:12

ChrisR



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!