askaale
askaale

Reputation: 1199

React Router 404 page

I am currently experiencing some issues regarding react router displaying of 404 not found-pages. This is the code I have so far:

 <Route path="/home" component={Home} exact={true}/>
 <Route path="/admin/forgot-password" component={AdminResetPassword} exact={true}/>
 <Authentication path="/admin/welcome" component={AdminWelcome} exact={true}/>
 <Authentication path="/admin/dashboard" component={AdminDashboard} exact={true}/>

However, if I try to do something like this:

<Route path="/home" component={Home} exact={true}/>
<Route path="/admin/forgot-password" component={AdminResetPassword} exact={true}/>
<Route path="*" component={Page404}/>
<Authentication path="/admin/welcome" component={AdminWelcome} exact={true}/>
<Authentication path="/admin/dashboard" component={AdminDashboard} exact={true}/>

The ting is, it works - but only for the pages that is not wrapped in authentication. In other words, if I was to try to navigate to an admin page, it just says 404 page not found. How would I fix this?

Help would be very appreciated.

Upvotes: 1

Views: 1804

Answers (2)

Ramdas Hedgapure
Ramdas Hedgapure

Reputation: 9

Starting from React Router v6, "Not Found" Routes can be used to achieve this

Syntax

<Route path="*" element={<NoMatch />} />

Example

<Routes>
  <Route path="/" element={<Layout />}>
  <Route index element={<SneakerGrid />} />
  <Route path="/sneakers/:id" element={<SneakerView />} />
 
  <Route path="*" element={<NoMatch />} />

</Routes>

Upvotes: 1

Colin Ricardo
Colin Ricardo

Reputation: 17249

You can use <Switch />:

<Switch>
    <Route path="/home" component={Home} exact={true}/>
    <Route path="/admin/forgot-password" component={AdminResetPassword} exact={true}/>
    <Authentication path="/admin/welcome" component={AdminWelcome} exact={true}/>
    <Authentication path="/admin/dashboard" component={AdminDashboard} exact={true}/>
    <Route component={Page404}/>
</Switch>

If none of the paths before the last one match, the Page404 will be shown.

Upvotes: 5

Related Questions