How to set the default route in ReactJS?

Duomly - Aug 2 '20 - - Dev Community

This article was originally published at https://www.blog.duomly.com/6-most-popular-front-end-interview-questions-and-answers-for-beginners-part-2/#how-to-set-default-route-in-react-js


Some time ago, we had an opportunity to use the component named “DefaultRoute” in the react routing.

Now, its depreciated method, and it’s not so popular to use it, you can create the custom route named default or whatever, but still, it’s not how we do it in modern React.js development.

It’s just because using the “DefaultRoute” route, we can cause some rendering problems, and its the thing that we definitely would like to avoid.

But don’t worry!

We have a solution to that problem, and I’d say its much more comfortable, but what more important, its a good practice.

To handle the default routing now, we can use two methods, one of them will be “*“, like routing, and the second one is “/”, that will redirect us to the defined component on the “default” path.

I’d recommend going with the “/” and set up the 404 component for the non-found pages instead of auto-redirect to the “default”.

Let’s see on the code example how it can be created.



<Switch>
  <Route path="/about">
    <About />
  </Route>
  <Route path="/contact/:id">
    <Contact />
  </Route>
  <Route path="/contact">
    <AllContacts />
  </Route>
  {/* The default route */}
  <Route path="/">
    <Home />
  </Route>
</Switch>


Enter fullscreen mode Exit fullscreen mode

Duomly - Programming Online Courses

Thank you for reading,
Radek from Duomly

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .