How to set a default route in React Router

#react

Last updated on Jun 15, 2021 by Suraj Sharma



In this tutorial, you will learn to set a default Route in React Router so that all the incorrect routes get redirected to the default route



Set a default route


To set the default Route, you have to use <Redirect /> component from the react-router-dom library.

import { Redirect } from 'react-router-dom';


First, define a <Routes /> component


./Routes.jsx

import { Switch, Route, Redirect } from 'react-router-dom';

const Routes = () => {

  return (
    <Switch>
      <Route exact path="/home" component={Home} />
      <Route exact path="/about" component={About} />
      <Route exact path="/contact" component={Contact} />
      <Route exact path="/services" component={Services} />
    </Switch>
  );
}

export default Routes;


Next, include the <Redirect /> component and pass the default route /home to the to attribute.


 <Switch>
  <Route exact path="/home" component={Home} />
  <Route exact path="/about" component={About} />
  <Route exact path="/contact" component={Contact} />
  <Route exact path="/services" component={Services} />
  <Redirect to="/home" />
</Switch>


Your default route is setup, now everytime a user hits an incorrect URL on the browser, the user will get redirected to the Home page of your application.


Note: Always include Redirect at the end, just before the </Switch> end tag, otherwise your default routing will not work.



Related Solutions


Rate this post


Suraj Sharma is a Full Stack Software Engineer. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.