Code Playground.

How to Set React Router Default Route Redirect to /home

CFG

How to Set React Router Default Route Redirect to /home

Routing permits us to design an application that acknowledges different URLs and is mapped to explicit parts. When the coordinating URL is discovered, at that point the coordinating page/part will be rendered into the HTML DOM. 

The Routing works by looking at the URL against the predefined rundown of courses in our React application. Each course is connected to a <Route> part where we have designed the total directing setup. 

In this guide, you will figure out how to begin with directing and divert the default course to/home. 

Routing Configuration

To begin with directing with React, you need first to introduce the library utilizing this npm order: 

npm install react-router-dom 

There are some key terms you should know to begin with the Routing arrangement. 

BrowserRouter 

BrowserRouter is the switch usage that utilizes the HTML5 history API to stay up with the latest with the program URL. 

It is BrowserRouter's duty to store all the parts and its Routes as an article. 

Switch 

Switch segments are utilized to render the default parts once the application rendered, and it will switch between Routes varying. 

Route 

The Route is an explanation that holds the particular way of the application alongside the segment's name and renders it once it coordinates the URL. 

Link 

The Link is like the HREF interface, which permits you to divert to the particular segments dependent on the predetermined way. 

Executing Default Route Redirect 

 

So far in this guide, you have figured out how to introduce the bundle and the terms that you are going to use for executing the directing. 

You can accomplish the switch setup by utilizing an API called BrowserRouter, which wraps all the parts that live in our React application 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 model, the <Router> is a parent part that wraps other kid segments as a <Route> that is associated with the particular segments. 

The subsequent stage is to make four distinct segments, as clarified underneath. 

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 straightforward segments that you are going to use for the directing for instance. Next, you'll proceed onward to the index.js document and glue the accompanying 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 segments in these segments: 

  • The primary area has the rundown of <Link> alongside a way for segments, so once a client taps on any of those Links, the switch finds the coordinating URL from the rundown of Routes 
  • The subsequent segment has the <Route> arrangement. Each Route has the name of the parts alongside the way presentation, so when the client taps on any <Link>, the coordinating <Route> is distinguished and rendered as needs be. 

The primary concern to see is that once the application is rendered, it will discover the way '/'. Be that as it may, the need is to divert to the/home way, which you can accomplish utilizing <Redirect> simply like this: 

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

In this code piece, the default application way for the underlying render is '/', so on the off chance that there is no way appended, at that point it ought to divert to the coordinating way, which is/home. 

The <Redirect> permits us to divert to the new segments dependent on the coordinating way from the present segments to other determined segments by abrogating the history object. 

Restrictively Redirect to the Default Path 

Up until this point, you have figured out how to divert the segments to a particular way. Be that as it may, in numerous situations, you might need to render explicit segments dependent on some condition. 

For this, you can utilize the ternary condition before diverting to the various parts, as clarified underneath. 

Set one Boolean variable into the state this way.: 

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

So before diverting to explicit segments, you have to ensure that whether the client is as of now signed in or not, the source code should resemble this: 

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

From the above model, you can see that when the way '/' is discovered, it will go to the render props where it recognizes that the client is signed in or not utilizing the this.state.isUserAuthenticated. In view of the worth, the divert will occur. 

This is the manner by which you can divert to explicit segments utilizing <Redirect> and furthermore do it restrictively. 

Conclusion 

The Routing is the main arrangement that any application needs, and you have learned perhaps the best ways to deal with divert segments to the default Route regardless of whether you have an unfilled way into the URL. 

Make a point to utilize these two methodologies in your React application to rearrange the directing. I trust this guide will be useful for you to gain proficiency with the best methodology.




CFG