Routing Part-7


In this article, we will continue discussing about Routing. 

In all our previous discussions about Routing, we have seen how we navigate from one Component to other Component by clicking on different links. 

There will be few scenarios where we have to do the navigation programmatically

Like for example, assume that we have three components, one is login, second one is home component and third one is edit profile. 

When a user is in login component, and when user enters the username and password, we validate the credentials and if the credentials are valid, we navigate user to the home component else we will display an error message. 

In this session, we will discuss about Programmatic navigation in React. 

Lets Open index.js file from our demo project. 

We will create four components. They are login, home, edit profile and app components. 

I have the code available handy for these components and I am pasting them one by one. 

Lets go to LogIn Component. On Click of the LogIn Button, we are calling onLogIn function. With in that function, lets call the Web API by sending the loginData object. Our Web API returns true or false as the response based on the login credentials. 

If we get true as the response, we have to navigate to home component. 

When a component is rendered by React Router, that component receives three different props: location, match, and history.

We have used match property in our previous sessions. 

History object has several properties and methods in it related to routing. One of the method is Push using which we can Push a new entry onto the history stack. 

Save the changes, navigate to the browser. 

Lets enter the wrong credentials first and one can we get the alert. 

Now I enter the Valid credentials and one can see that we are navigated to Home Component. 

The other methods available on History object are, 

Replace- This method Replaces the current entry on the history stack. 

Lets understand the difference between push and replace through our Program. 

Add a button to the contents of homecomponent. 

On Click of that button, lets navigate to edit profile component using push method. 

Now I enter the Valid credentials and one can see that we are navigated to Home Component. 

When we click on Next button, we are navigated to Edit Profile Component. 

Our history object has the complete track of our navigation paths. If we click on browser back button, we go back to Home Component. Click on Back button again, we go back to LogIn Component. 

Now instead of push method, we will navigate to edit profile component using replace method. 

Lets repeat the same steps and we go to Edit Profile Component. 

As we have used replace method, which replaces the history stack. Click on Back button, one can observe that we have been navigated to the Login Component but not to home component. 

go(n) - (function) Moves the pointer in the history stack by n entries

goBack() - (function) Equivalent to go(-1)

goForward() - (function) Equivalent to go(1)

block(prompt) - (function) Prevents navigation

import React, { useState } from 'react';
import ReactDOM from 'react-dom';
import {BrowserRouter, Link, NavLink, Switch, Route} from 'react-router-dom';

function LogIn(props){
  const [loginData,setLoginData]=useState({username:'',password:''});

  function changeLogInData(e){
    setLoginData({...loginData,[e.target.name]:e.target.value});
  }

  function onLogIn(){
    fetch("https://localhost:44306/api/Test",{
      method:'POST',
      headers:{'Content-type':'application/json'},
      body:JSON.stringify(loginData)
    }).then(r=>r.json()).then(result=>{
      if(result){
        props.history.push('/home');
      }
      else{
        alert('Invalid UserName or PassWord');
      }
    });
  }

  return(
    <div>
      <h2>Welcome to LogIn...</h2>
      <p>
        <label>UserName : <input type="text" value={loginData.username} 
                          name="username" onChange={changeLogInData}></input></label>
      </p>
      <p>
        <label>PassWord : <input type="text" value={loginData.password} 
                          name="password" onChange={changeLogInData}></input></label>
      </p>
      <button onClick={onLogIn}>LogIn</button>
    </div>
  )
}

function Home(props){
  function onNext(){
    props.history.replace('/editprofile');
  }
  return(
    <div>
      <h2>Welcome to Home...</h2>  
      <button onClick={onNext}>Next</button>    
    </div>
  );
}
function EditProfile(){
  return(
    <div>
      <h2>Welcome to Edit Profile...</h2>
    </div>
  );
}

function App(){
  return(
    <div>
      <h2>Welcome to App Component...</h2>
      <Link to="/">LogIn</Link>&nbsp;&nbsp;
      <NavLink to="/home" activeClassName="testClass">Home</NavLink>&nbsp;&nbsp;
      <NavLink to="/editprofile" activeClassName="testClass">Edit Profile</NavLink>
      
      <Switch>
        <Route exact path="/" component={LogIn}></Route>
        <Route path="/home" component={Home}></Route>
        <Route path="/editprofile" component={EditProfile}></Route>
      </Switch>
      
    </div>
  )
}

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

Video Reference:





© 2020 Pragimtech. All Rights Reserved.