0

I am building a web app with different routes.

There is this case where if a user hits any arbitrary route then he gets directed to Login Component. But it only handles case where bad routing happens this way localhost:3000/gvgdvgdvgd.

I have routes such as /home/news. A user may end up hitting /home/news/10 manually which doesn't exist. Similarly there is a route such as coupon and user may end up hitting /coupons/88 without going to coupons first.

How do I handle these issues in my web-app? I handled it for the first case. Here is the routing config.

    <Route path="/login" component={LoginLoadable} />
    <Route path="/home" component={Home} />
    <Route path="/maths" component={Maths} />
    <Route
     exact
     path="/"
    render={routeProps => (
       <Component1
        {...routeProps}
      />
     )}
   />
   <Route component={LoginLoadable}/>

What about the case where user hits maths/123/1ydhd manually when that doesn't exist?

dfsdigging
  • 345
  • 1
  • 4
  • 15
  • check out [https://stackoverflow.com/questions/51457480/react-router-4-catch-all-route](https://stackoverflow.com/questions/51457480/react-router-4-catch-all-route) – Chandan Mar 18 '19 at 18:34

1 Answers1

0

Wrap your routes in a Switch and add a Route with no path prop that renders your 404 page. If you don't specify a path, it should always render that route. Adding a Switch makes sure only one route will render. Also you will need to add the exact prop to your routes. See: https://reacttraining.com/react-router/web/api/Route/exact-bool for how it matches sub-routes.

Something like:

<Switch>
    <Route path="/login" component={LoginLoadable} />
    <Route exact path="/home" component={Home} />
    <Route exact path="/maths" component={Maths} />
    <Route
     exact
     path="/"
    render={routeProps => (
       <Component1
        {...routeProps}
      />
     )}
   />
   <Route component={LoginLoadable}/> // <-- remove this since you render it in '/login'
   <Route component={A404Page} // <-- add this
</Switch>
dev
  • 863
  • 7
  • 14