0

Two Pages(Products & Edit Product page) overlapping each other after clicking edit button. Instead of redirect to edit page, it is coming under the current page.

Here is my file contents. https://codesandbox.io/s/mmwqz8lz8p

Here is my file contents.

Suman
  • 219
  • 2
  • 11

2 Answers2

2

Use exact in products route.

Because product edit path/link /products/:id is sub-link of product link /products. When you set path without exact and go to product edit link /products/:id it contain path for product /products and product edit /products/:id both. Then why when you go to product edit page both routes is working and products and editProduct both component is showing.

To fix this you have to use exact attribute true for product route. Just like following

<Route exact path='/products' component={products}/>
webHasan
  • 338
  • 2
  • 10
  • What's the need? – Suman Oct 21 '18 at 12:47
  • Edited answer. If you like learn more about `exact` attribute [read this ans](https://stackoverflow.com/questions/49162311/react-difference-between-route-exact-path-and-route-path.) – webHasan Oct 21 '18 at 13:01
1

Given that you use Switch Component in your code like

<Router>
   <Switch>
      <div className="App">
        <Route path='/' exact={true} component={loginscreen}/>
        <Route path='/users' exact={true} component={users}/>
        <Route path='/users/:id' component={userEdit}/>
        <Route path='/products' component={products}/>
        <Route path='/products/:id' component={editProduct}/>
        <Route path='/addproducts' component={addProduct}/>
        <Route path='/album' component={album}/>
        <Route path='/main' component={main}/>
      </div>
   </Switch>
 </Router>

The behaviour that you describe would be different from what you describe in your question. Switch component matches the first Route and skips the rest. Also the way React router match works is that any Route path will also match its Prefix Routes, for example, /products/:id will also match /products and without the use of Switch all matches will be rendered.

As per your above configuration, /products/:id will also render /products page only. In order for it to work correctly, just reverse the order of your Routes,

 <Switch>
      <div className="App">
        <Route path='/' exact={true} component={loginscreen}/>
        <Route path='/users' exact={true} component={users}/>
        <Route path='/users/:id' component={userEdit}/>
        <Route path='/products/:id' component={editProduct}/>
        <Route path='/products' component={products}/>
        <Route path='/addproducts' component={addProduct}/>
        <Route path='/album' component={album}/>
        <Route path='/main' component={main}/>
      </div>
   </Switch>

P.S. As a rule, all prefix Routes must be written later in the order.

Shubham Khatri
  • 211,155
  • 45
  • 305
  • 318