Categories
React Answers

How to add a not found route with React Router?

Spread the love

Sometimes, we want to add a not found route with React Router.

In this article, we’ll look at how to add a not found route with React Router.

How to add a not found route with React Router?

To add a not found route with React Router, we can use the Switch component.

For instance, we write

<Switch>
  <Route path="/users" component={MyComponent} />
  <Route path="/404" component={GenericNotFound} />
  <Redirect to="/404" />
</Switch>

to wrap the Switch component around the Route components.

We add the Route with path /404 at the end so it’ll only be loaded when nothing else matches.

Also, we add a Redirect component to redirect to /404 if nothing else matches.

Conclusion

To add a not found route with React Router, we can use the Switch component.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *