Skip to content

Contact sales

By filling out this form and clicking submit, you acknowledge our privacy policy.

How to Set React Router Default Route Redirect to /home

Nov 12, 2020 • 8 Minute Read

Introduction

Routing allows us to configure an app that accepts various URLs and is mapped to specific components. Once the matching URL is found, then the matching page/component will be rendered into the HTML DOM.

The routing works by comparing the URL against the specified list of routes in our React app. Each route is linked to a <Route> component where we have configured the complete routing configuration.

In this guide, you will learn how to get started with routing and redirect the default route to /home.

Routing Configuration

To get started with routing with React, you need first to install the library using this npm command:

      npm install react-router-dom
    

There are some key terms you should know to get started with the routing configuration.

BrowserRouter

BrowserRouter is the router implementation that uses the HTML5 history API to keep your UI up to date with the browser URL.

It is BrowserRouter’s responsibility to store all the components and its routes as an object.

Switch

Switch components are used to render the default components once the app rendered, and it will switch between routes as needed.

Route

The route is a statement that holds the specific path of the app along with the component’s name and renders it once it matches the URL.

The link is similar to the HREF link, which allows you to redirect to the specific components based on the specified path.

Implementing Default Route Redirect

So far in this guide, you have learned how to install the package and the terms that you are going to use for implementing the routing.

You can achieve the router configuration by using an API called BrowserRouter, which wraps all the components that reside in our React app like this.:

      <Router>
    <Switch>
        <Route exact path="/path1" component={comp1} />
        <Route exact path="/path2" component={comp2} />
        <Route exact path="/path3" component={comp3} />
        <Route exact path="/path4" component={comp4} />
    </Switch>
</Router>
    

In the above example, the <Router> is a parent component that wraps other child components as a <Route> that is connected to the specific components.

The next step is to create four different components, as explained below.

Home.jsx

      import React from 'react';
export default Home => <div>This is home component</div>;
    

Test1.jsx

      import React from 'react';
export default Test1 => <div>This is Test1 component</div>;
    

Test2.jsx

      import React from 'react';
export default Test2 => <div>This is Test2 component</div>;
    

Test3.jsx

      import React from 'react';
export default Test3 => <div>This is Test3 component</div>;
    

These are the four simple components that you are going to use for the routing as an example. Next, you'll move on to the index.js file and paste the following lines of source code:

      import React, { Component } from "react";
import { render } from "react-dom";
import {
  BrowserRouter as Router,
  Switch,
  Route,
  Link,
  Redirect
} from "react-router-dom";
import Home from "./Home";
import Test1 from "./Test1";
import Test2 from "./Test2";
import Test3 from "./Test3";

class App extends Component {
  constructor() {
    super();
    this.state = {
      name: "React",
      isUserAuthenticated: true
    };
  }

  render() {
    return (
      <div>
        <Router>
          <div>
            <ul>
              <li>
                <Link to="/home">Home</Link>
              </li>
              <li>
                <Link to="/test1">Test 1</Link>
              </li>
              <li>
                <Link to="/test2">Test 2</Link>
              </li>
              <li>
                <Link to="/test3">Test 3</Link>
              </li>
            </ul>
            <hr />
            <Switch>
              <Route
                exact
                path="/"
                render={() => {
                    return (
                      this.state.isUserAuthenticated ?
                      <Redirect to="/home" /> :
                      <Redirect to="/test1" /> 
                    )
                }}
              />
               <Route exact path="/home" component={Home} />
              <Route exact path="/test1" component={Test1} />
              <Route exact path="/test2" component={Test2} />
              <Route exact path="/test3" component={Test3} />
            </Switch>
          </div>
        </Router>
      </div>
    );
  }
}

render(<App />, document.getElementById("root"));
    

There are two sections in these components:

  • The first section has the list of <Link> along with a path for components, so once a user clicks on any of those links, the router finds the matching URL from the list of routes

  • The second section has the <Route> configuration. Each route has the name of the components along with the path declaration, so when the user clicks on any <Link>, the matching <Route> is identified and rendered accordingly.

The main thing to notice is that once the app is rendered, it will find the path ‘/’. However, the need is to redirect to the /home path, which you can achieve using <Redirect> just like this:

      <Route exact path="/">
    <Redirect to="/home" />
</Route>
    

In this code snippet, the default app path for the initial render is ‘/’, so if there is no path attached then it should redirect to the matching path, which is /home.

The <Redirect> allows us to redirect to the new components based on the matching path from the current components to other specified components by overriding the history object.

Conditionally Redirect to the Default Path

So far, you have learned how to redirect the components to a specific path. But in many scenarios, you may want to render specific components based on some condition.

For this, you can use the ternary condition before redirecting to the different components, as explained below.

Set one Boolean variable into the state like this.:

      constructor() {
    super();
    this.state = {
      isUserAuthenticated: true
    };
}
    

So before redirecting to specific components, you need to make sure that whether the user is already logged in or not, the source code should look like this:

      <Route
    exact
    path="/"
    render={() => {
        return (
            this.state.isUserAuthenticated ?
            <Redirect to="/home" /> :
            <Redirect to="/test1" /> 
        )
    }}
/>
    

From the above example, you can see that when the path ‘/’ is found, it will go to the render props where it identifies that the user is logged in or not using the this.state.isUserAuthenticated. Based on the value, the redirect will happen.

This is how you can redirect to specific components using <Redirect> and also do it conditionally.

Conclusion

The routing is the first configuration that any app needs, and you have learned one of the best approaches to redirect components to the default route even if you have an empty path into the URL.

Make sure to use these two approaches in your React app to simplify the routing. I hope this guide will be helpful for you to learn the best approach. If you have any queries, feel free to reach out at Codealphabet.

Learn More

Explore these React courses from Pluralsight to continue learning: