-1

I have the following routes in my react app:

<Route exact path="/" component={HomeScreen} />
<Route exact path="/:category" component={HomeScreen} />
<Route exact path="/:category/:id" component={PostDetailScreen} />
<Route exact path="/posts/new" component={CreatePostScreen} />

When I go to /posts/new my app not only renders CreatePostScreen but also PostDetailScreen. I think it interprets :category = posts and :id = new.

However, I am stuck. What am I doing wrong? I just want to have the /posts/new route rendering CreatePostScreen.

Oliver
  • 1,051
  • 1
  • 8
  • 27
  • If you use exact, it shouldn't render both the components, Also check this https://stackoverflow.com/questions/43994510/react-router-v4-renders-multiple-routes/43994605#43994605 – Shubham Khatri May 02 '18 at 12:52

2 Answers2

1

React router interprets “posts” as a category and “new“ as ID.

Change the order of the Route components, and use a Switch component, like this:

<Switch>
    <Route exact path="/" component={HomeScreen} />
    <Route exact path="/posts/new" component={CreatePostScreen} />
    <Route exact path="/:category" component={HomeScreen} />
    <Route exact path="/:category/:id" component={PostDetailScreen} />
</Switch>
Patrick Hund
  • 14,392
  • 8
  • 50
  • 77
1

Try this

<Switch>
  <Route exact path="/" component={HomeScreen} />
  <Route exact path="/posts/new" component={CreatePostScreen} />
  <Route exact path="/:category" component={HomeScreen} />
  <Route exact path="/:category/:id" component={PostDetailScreen} />
</Switch>

/posts/new is a valid path that satisfies /:category/:id i.e. your category is posts id is new

Placing routes in <Switch> renders first one that matches, more info here https://reacttraining.com/react-router/web/api/Switch

Ilja
  • 35,872
  • 66
  • 218
  • 401