Search code examples
javascriptreactjsreact-routerreact-router-dom

react-router paths keep redirecting to 404


I have a router link that works successfully taking me to a product-management page:

<Route
  path='/auth/products/product-management'
  render={() => <ProdManagement {...this.props} />}
/>
<Redirect path="*" to="/404" />

Inside the ProdManagement component I have two buttons that onClick should take me to other pages:

const addProduct = () => {
  props.history.push('/auth/products/add-product')
}
const editProduct = () => {
  props.history.push('/auth/products/edit-product')
}

The return for ProdManagement component has the routes set looks like this:

return (
  <div> 
    <Switch>         
      <Route
        exact
        path='/auth/products/add-product'
        render={() => <AddProduct {...this.props} />}
      />
      <Route
        exact
        path='/auth/products/edit-product'
        render={() => <EditProduct {...this.props} />}
      />
    </Switch>
  </div>
)

But every time I click the buttons I get sent to the 404 page. Anyone have an idea what I'm doing wrong here? I know the addProduct() function is being called as I log something to the console.

UPDATE: I moved the two routes (add & edit) to the same level as the main /auth/products/product-management and they work now. Not sure why, but it fixed them.


Solution

  • The ProdManagement component is rendered on path "/auth/products/product-management" and when it triggers navigation actions to paths "/auth/products/add-product" or "/auth/products/edit-product" the path now no longer matches "/auth/products/product-management" and ProdManagement is unmounted so the other paths are not mounted and <Redirect path="*" to="/404"/> is what is left to render.

    As it seems you've discovered, the easy solution is to just declare the routes where they are always mounted and matchable.

    <Switch>
      ... other more specific routes ...
    
      <Route
        path="/auth/products/product-management"
        component={ProdManagement}
      />
      <Route exact path="/auth/products/add-product" component={AddProduct} /> 
      <Route exact path="/auth/products/edit-product" component={EditProduct} />
    
      ... other less specific routes ...
     
      <Redirect path="*" to="/404" />
    </Switch>