⚠️ This lesson is retired and might contain outdated information.

Render Catch-All Routes with React Router v4 using the Switch Component

Joe Maddalone
InstructorJoe Maddalone
Share this video with your friends

Social Share Links

Send Tweet
Published 7 years ago
Updated 2 years ago

There are many cases where we will need a catch-all route in our web applications. This can include 404-style routes when nothing is match or other use cases where where we receive an invalid route in React Router v4.

[00:00] In our application, I'm going to create a link for contact, and it's going to link to a path that doesn't exist, forward slash contact. When I run this, we have our home route, we have our about route, and when I go to contact, nothing is going to runner.

[00:17] One feature of react-router that we can employ here, is the fact that a route without a path will always render. Here I'm creating a route with no path, I'm just going to say, "Page not found." I save that, and we're here on this contact route which we haven't defined, we get our page not found.

[00:37] However, if I go to about or home, we're still getting our page not found, because that route is always going to render.

[00:44] To solve that, we can bring in the switch component. To use the switch component, we're going to wrap our route in that component, these routes are now children of that component, and what switch will do is only render the first route that matches. If I save this, here on our home route we just get our home. On about, we just get about, and on contact we've got our page not found.

[01:11] That would work for any route. If I just make up some stuff here, save it, and we go to that route, we're still going to get our page not found, and the rest of our routes are going to render just fine.

egghead
egghead
~ 18 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today