Home > Software design >  React Js navigate between pages using Navigate inside the button click event
React Js navigate between pages using Navigate inside the button click event

Time:04-04

I am using latest version of the react js. I want to navigate the add page to after login. here is the my code.

import React,{Component} from 'react';
import { variables } from '../../Variables';
import { Navigate } from 'react-router-dom';



export class Login extends Component{

constructor(props){
    super(props);
    this.state={
        login:[],
        name:"",
        password:"",
        redirect: false
    }
}

changelogindetailsname = (e)=>{
    this.setState({name:e.target.value})
}

changelogindetailspass = (e)=>{
    this.setState({password:e.target.value})
}

loginClick(){
    
        fetch(variables.API_URL 'login',{
            method:'POST',
            headers:{
                'Accept':'application/json',
                'Content-Type':'application/json'
            },
            body:JSON.stringify({
                name:this.state.name,
                password:this.state.password
            })
            
        })
        .then(res=>res.json())
        .then((result)=>{
            alert(result);
            const navigate = Navigate();                
          navigate("/add" , { replace: "/" } );

             
        },(error)=>{
            alert('Faild');
        })
    }


render(){
    const{
        name,
        password
    }=this.state;
    return(
            <div>
                <center>
                    <h1></h1>
                    <hr/>
                    <h3>Welcome Back !</h3>
                    <p></p>
                    <div className="container">
                        <br/>
                        <br/>
                        <br/>
                        <div className="row">
                            <div className="col">

                            </div>
                            <div className="col">

                            </div>
                            <div className="col-4">
                            <style>{"\ .rr{\ float:left;\ }\ "} </style>
                            <style>{"\ .bb{\ float:right;\ }\ "} </style>
                                <div className="mb-3">
                                    <label className="form-label rr d-flex"> Username</label>
                                    <div className="input-group input-group-lg">
                                        <input type="text" className="form-control " id="formGroupExampleInput" placeholder="Username"
                                        value={name}
                                        onChange={this.changelogindetailsname}/>
                                    </div>
                                </div>
                                <div className="mb-3">
                                    <label className="form-label rr d-flex">Password</label>
                                    <div className="input-group input-group-lg">
                                        <input type="password" className="form-control" id="formGroupExampleInput2" placeholder="Password"
                                        value={password}
                                        onChange={this.changelogindetailspass}/>
                                    </div>
                                </div>
                                <div className="d-flex mb-3">
                                    <a href="#" className="form-label rr"> Forgot your password?</a>
                                </div>
                                <div className="col">
                                        <div className="form-check rr">
                                            <input className="form-check-input" type="checkbox" value="" id="flexCheckDefault"/>
                                            <label className="form-check-label" htmlFor="flexCheckDefault">
                                                Remember me
                                            </label>
                                        </div>
                                </div>
                                   
                                <div className="col">
                                    <button type="button" className="btn btn-success bb"
                                    onClick={()=>this.loginClick()} navigate="/Add.js" >Login</button>
                                </div>
                                   
                                <br/>
                                <br></br>
                                <hr/>
                                <p>Don't have an account?</p>
                                <div className="mb-3">
                                    
                                     <button type="button" className="btn btn-light d-flex"
                                     href="Add.js" >Sign up for Muessoze</button>
                           
                                  </div>
                            </div>
                            <div className="col">
                                
                            </div>
                            <div className="col">
                                
                            </div>
                        </div>

                      
                   
                    </div>
                   
                </center>
            </div>
    )
}

}

This is compile without error but the runtime browser console get this error

Uncaught (in promise) TypeError: Cannot destructure property 'to' of '_ref2' as it is undefined. at Navigate (index.tsx:165:1) at Login.js:44:1

This is the App.js file code

  import { BrowserRouter, Route, Routes } from 'react-router-  dom';
  import './App.css';
  import { Login } from './components/Login/Login';
  import { Add } from './components/Login/Add';

  function App() {
     return (
       <BrowserRouter>
          <Routes>
             <Route exact path="/" element={<Login/>}/>
             <Route exact path="/add" element={<Add/>}/>
          </Routes>
       </BrowserRouter>
     );
   }

   export default App;

I have no idea what to do, I tried several times but problem is the same. I think passing parameters is the reason for this error. but still I have no solution for this. please help me.

CodePudding user response:

EDIT ( After OP clarified he is using a class Component ):

Since you are using a class component, you can't use Hooks (Please switch to function components, most react class based code is legacy code! ), but you can decorate your Component with a HOC and pass navigate to it as a prop, we answered a few hours ago to a very similar question :

HOC:

const withNavigate = Component => props => {
  const navigate = useNavigate();
  const params = useParams();

  return <Component {...props} params={params} navigate={navigate} />;
}

const LoginWithNavigate = withNavigate(Login);

Then in your Login Component you can just do this.props.navigate("/") to navigate.


Delete const navigate = Navigate();
Navigate is a React Component you can't use it like that, to use navigate like that you need to use useNavigate hook .

Import {useNavigate} from "react-router-dom"

then inside your React component:

const navigate = useNavigate()            

Now it should work, just change replace prop to a boolean value.

  • Related