Reputation: 3844
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:
Actual Result:
The page does not forward users to the "/request" path.
Would you tell me what the problem is?
Upvotes: 2
Views: 174
Reputation: 3905
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 {
... }
}
}
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
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