Author avatar

Gaurav Singhal

How to Set React Router Default Route Redirect to /home

Gaurav Singhal

  • May 1, 2020
  • 7 Min read
  • 15,525 Views
  • May 1, 2020
  • 7 Min read
  • 15,525 Views
Web Development
Front End Web Development
Client-side Framework
React

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:

1
npm install react-router-dom 
powershell

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.

Link

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.:

1
2
3
4
5
6
7
8
<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>
jsx

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

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

Test1.jsx

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

Test2.jsx

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

Test3.jsx

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

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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
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"));
jsx

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:

1
2
3
<Route exact path="/">
    <Redirect to="/home" />
</Route>
jsx

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.:

1
2
3
4
5
6
constructor() {
    super();
    this.state = {
      isUserAuthenticated: true
    };
}
jsx

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:

1
2
3
4
5
6
7
8
9
10
11
<Route
    exact
    path="/"
    render={() => {
        return (
            this.state.isUserAuthenticated ?
            <Redirect to="/home" /> :
            <Redirect to="/test1" /> 
        )
    }}
/>
jsx

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.

23