DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Cover image for How to set the default route in ReactJS?
Duomly
Duomly

Posted on • Originally published at blog.duomly.com

How to set the default route in ReactJS?

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>

Duomly - Programming Online Courses

Thank you for reading,
Radek from Duomly

Top comments (0)

🌚 Life is too short to browse without dark mode