ousmane784
ousmane784

Reputation: 456

React Router 404 - NotFound page does not show

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

Upvotes: 2

Views: 627

Answers (1)

Drew Reese
Drew Reese

Reputation: 203418

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".

Upvotes: 1

Related Questions