The KNVB
The KNVB

Reputation: 3844

How can I forward the user to other page/path in react?

I am implementing a simple login page, and I want to forward the user to another page/path after selecting an identity.

import {useState} from "react";
import { Navigate } from 'react-router-dom';
import Container from 'react-bootstrap/Container';
import Select from 'react-select';
import './Login.css';

export default function Login(){
    const [technician,setTechnician]=useState();
    let options=[
        {label:"Jack", value:"2432244cvdsffsd2342434"}
    ];

    let doLogin=()=>{
        if (technician){
            sessionStorage.setItem("technican",JSON.stringify(technician));
            return <Navigate to='/request'/>
        }else {
            alert("Please select your name to login.");
        }
    }
    let handleChange=(value)=>{
        setTechnician(value);
    }
    return (
        <Container>
            Login:
            <Select
                isClearable
                onChange={handleChange}
                options={options} 
                placeholder="Please select your name to login"/>
            <button onClick={doLogin}>Login</button>    
        </Container>
    )
}

I am using react-router v6.

"react-router-dom": "^6.0.2"

Expected Result:

  1. user selects identity from the drop-down.
  2. Click on the "login" button. It should forward the user to the "/request" path

Actual Result:

The page does not forward users to the "/request" path.

Would you tell me what the problem is?

Upvotes: 2

Views: 174

Answers (2)

MagnusEffect
MagnusEffect

Reputation: 3905

  • For the version of react router dom less than 6.^

You can use useHistory() hook like this.

import { useHistory } from 'react-router-dom';
...
export default function Login(){
   let history = useHistory();
   ...
    let doLogin=()=>{
      if (technician){
        ...
        history.push('/request');
      }
      else {
        ...     }
   }
}
  • For the latest version of react router dom greater than 6.^

You can use useNavigate() hook like this.

import { useNavigate } from 'react-router-dom';
...
export default function Login(){
   let navigate = useNavigate();
   ...
    let doLogin=()=>{
      if (technician){
        ...
        navigate('/request');
      }
      else {
        ...     }
   }
}

Upvotes: 1

Saeed Shamloo
Saeed Shamloo

Reputation: 6554

You can do it by useNavigate hook in react-router-dom v6, like this:

import { useNavigate } from 'react-router-dom';
...
export default function Login(){
   const navigate = useNavigate();
   ...
    let doLogin=()=>{
      if (technician){
        sessionStorage.setItem("technican",JSON.stringify(technician));
        navigate('/request');
      }else {
        alert("Please select your name to login.");
     }
   }
}

Upvotes: 1

Related Questions