Can't display routes properly in react

Viewed 199

Hi I have this routes in App.js

function App() {
  return (
    <BrowserRouter>
      <Switch>
        <Route key="products" path="/products" component={Products}></Route>
        <Route key="preview" path="/products/:id" component={Preview}></Route>
        <Route key="add-product" path="/products/create" component={ProductCreate}></Route>
        <Route key="edit-product" path="/products/:id/edit" component={ProductEdit}></Route>
        <Route exact path="/" component={Home}></Route>
      </Switch>
    </BrowserRouter>
  );
}

it displays only /products and / others are not displayed they get Products component displayed and I don't understand why. For example my product edit looks like this:

import React from 'react';

const ProductEdit = (props) => {
  return(
    <div>
      <p>Product Edit page</p>
    </div>
  )
}

export default ProductEdit;

and this is the result I get:

enter image description here

Can't find the problem my self...

2 Answers

You must organise paths within Switch such that the prefix paths are at the end.

The issue with the current code is that when you are on path say /products/:id, it matches path /products too since it is prefix path and hence it only renders Products Component as Switch renders just the first matching Route

The reordered version of your paths will be as follows

<BrowserRouter>
  <Switch>
    <Route key="edit-product" path="/products/:id/edit" component={ProductEdit}></Route>
    <Route key="add-product" path="/products/create" component={ProductCreate}></Route>
    <Route key="preview" path="/products/:id" component={Preview}></Route>
    <Route key="products" path="/products" component={Products}></Route>
    <Route exact path="/" component={Home}></Route>
  </Switch>
</BrowserRouter>

/products/:id path will match /products/create and also /products/:id/edit and as you are using Switch, once the route matches, no further routes will be rendered.

Reordering Route components will solve the problem

<Route key="edit-product" path="/products/:id/edit" component={ProductEdit}></Route>
<Route key="add-product" path="/products/create" component={ProductCreate}></Route>
<Route key="preview" path="/products/:id" component={Preview}></Route>
Related