DEV Community

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

Posted on • Originally published at blog.duomly.com

10 1

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>


Enter fullscreen mode Exit fullscreen mode

Duomly - Programming Online Courses

Thank you for reading,
Radek from Duomly

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay