React Router 404 - NotFound page does not show

Viewed 129

I have a react router switch and the 404 page doesnt work

<Switch>
 <Route path="/login" component={Login} />
 <Layout>
  <ProtectedRoute exact path="/home" component={Home} />
  <ProtectedRoute exact path="/profiles" component={Profiles} />
  <ProtectedRoute exact path="/profiles/alarms" component={Alarms} />
  <ProtectedRoute exact path="/profiles/:id" component={Profile} />
 </Layout>
 <ProtectedRoute component={NotFound} />
</Switch>

Whenever I change the url to a random one like '/tewyu'. The page just shows blank it doesnt go to the 404 page. It feels like one of the routes are catching it

1 Answers

Sounds like you have two basic views, your app with a navbar and specific layout, and a authentication page.

You can wrap the nested Layout component in a general route and render the nested routes into another Switch for matching.

<Switch>
  <Route path="/login" component={Login} />
  <Route>
    <Layout> // <-- navbar and layout
      <Switch>
        <ProtectedRoute exact path="/home" component={Home} />
        <ProtectedRoute exact path="/profiles" component={Profiles} />
        <ProtectedRoute exact path="/profiles/alarms" component={Alarms} />
        <ProtectedRoute exact path="/profiles/:id" component={Profile} />
        <ProtectedRoute component={NotFound} />
      </Switch>
    </Layout>
  </Route>
</Switch>

Of course, you could also make the general Route component a ProtectedRoute and then render normal Route components within this auth "checkpoint".

Related