Check your version
This post assumes you're using React Router v6. If not, find your version below.

React Router is all about mapping URL paths to React components. However, sometimes you want React Router to render a component when none of the Routes match.

The most common use case for this is showing a 404 page. Regardless of if you want to show off your creative side or not, having a 404 page in place is a small thing that will go a long way for the UX of your site. Luckily, this is pretty simple to do with React Router’s Routes component.

Routes is the powerhouse of React Router. Whenever the app’s location changes, any Routes component will look through all its children Route elements to find the best match to render.

<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/settings" element={<Settings />} />
</Routes>

Unlike previous versions of React Router, the order of the children Routes doesn’t matter since Routes is intelligent – meaning an algorithm now determines which is the best Route to render. This makes rendering a 404 component pretty simple.

All you have to do is render a Route with a path of *, and React Router will make sure to only render the element if none of the other Routes match.

<Routes>
<Route path='*' element={<NotFound />} />
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/settings" element={<Settings />} />
</Routes>
Want to learn more?
If you liked this post and want to learn more, check out our free Comprehensive Guide to React Router.

Before you leave

I know, "another newsletter pitch" - but hear me out. Most JavaScript newsletters are terrible. When's the last time you actually looked forward to getting one? Even worse, when's the last time you actually read one rather than just skim it?

We wanted to change that, which is why we created Bytes. The goal was to create a JavaScript newsletter that was both educational and entertaining. 84,338 subscribers and an almost 50% weekly open rate later, it looks like we did it.

Delivered to 84,338 developers every Monday

Avatar for Tyler McGinnis

Tyler McGinnis

CEO of ui.dev. Obsessed with teaching, writing, swimming, biking, and running.

Share this post

Want more react-router?

This is part of our React Router course. You can take the rest of the course by starting a free 3-day trial.