React-Router: No Not Found Route?

DefaultRoute and NotFoundRoute were removed in react-router 1.0.0.

I’d like to emphasize that the default route with the asterisk has to be last in the current hierarchy level to work. Otherwise it will override all other routes that appear after it in the tree because it’s first and matches every path.

For react-router 1, 2 and 3

If you want to display a 404 and keep the path (Same functionality as NotFoundRoute)

<Route path="*" exact={true} component={My404Component} />

If you want to display a 404 page but change the url (Same functionality as DefaultRoute)

<Route path="/404" component={My404Component} />
<Redirect from='*' to='/404' />

Example with multiple levels:

<Route path="https://stackoverflow.com/" component={Layout} />
    <IndexRoute component={MyComponent} />
    <Route path="https://stackoverflow.com/users" component={MyComponent}>
        <Route path="user/:id" component={MyComponent} />
        <Route path="*" component={UsersNotFound} />
    </Route>
    <Route path="/settings" component={MyComponent} />
    <Route path="*" exact={true} component={GenericNotFound} />
</Route>

For react-router 4 and 5

Keep the path

<Switch>
    <Route exact path="https://stackoverflow.com/users" component={MyComponent} />
    <Route component={GenericNotFound} />
</Switch>

Redirect to another route (change url)

<Switch>
    <Route path="https://stackoverflow.com/users" component={MyComponent} />
    <Route path="/404" component={GenericNotFound} />
    <Redirect to="/404" />
</Switch>

The order matters!

Leave a Comment