0

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.

  • `replace` property is a boolean value, but I don't think this is the cause of any issue. What line of code is `TypeError: Cannot destructure property 'to' of '_ref2' as it is undefined. at Navigate (index.tsx:165:1) at Login.js:44:1` occurring on? – Drew Reese Apr 03 '22 at 23:49
  • 1
    I doubt on your `const navigate = Navigate(); ` placement. Isn't it a `hook` call? It's supposed to be on the top part of the component and not inside any blocks. – Sanish Joseph Apr 03 '22 at 23:54
  • Oh, `Navigate` is the React component. Did you mean to import `useNavigate` and use that as a hook at the top of your React component? Please edit your question to include a [minimal, complete, and reproducible code example](https://stackoverflow.com/help/minimal-reproducible-example) so we can more clearly see what the code is trying to do. – Drew Reese Apr 03 '22 at 23:56
  • I thought he is using `useNavigate`. – Sanish Joseph Apr 03 '22 at 23:57
  • Login.js:44:1 is the navigate("/add" , { replace: "/" } ); line – Bavindu Dissanayake Apr 03 '22 at 23:59
  • I updated my full code for the question – Bavindu Dissanayake Apr 04 '22 at 00:02

1 Answers1

1

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.

Cesare Polonara
  • 3,473
  • 1
  • 9
  • 19
  • Firstly I tried that but , It's make router hook error – Bavindu Dissanayake Apr 04 '22 at 00:03
  • Be sure you are using react-router@latest v^6. Be sure you are using a functional React component, not a class. – Cesare Polonara Apr 04 '22 at 00:04
  • Uncaught (in promise) Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons: 1. You might have mismatching versions of React and the renderer (such as React DOM) 2. You might be breaking the Rules of Hooks 3. You might have more than one copy of React in the same app – Bavindu Dissanayake Apr 04 '22 at 00:04
  • This is the error useNavigate function gave – Bavindu Dissanayake Apr 04 '22 at 00:05
  • Paste in your question all your React component code, so we can understand where you are trying to use that hook. – Cesare Polonara Apr 04 '22 at 00:05
  • I update the question – Bavindu Dissanayake Apr 04 '22 at 00:11
  • Yes, you are in a class and you can't use hooks in a class, I updated the answer with the solution. – Cesare Polonara Apr 04 '22 at 00:14
  • Which place HOC is need place ? Inside the App() function or Outside of that ? – Bavindu Dissanayake Apr 04 '22 at 00:22
  • The HOC is just a function, you can write it in a separate module and import it in the modules with the Component that you want to enhance. They have to be applied outside of React components since when you put something inside a React Component it enters the React lifecycle and you dont need this logic to be in the lifecycle of your app, but it has to be executed only once. Be sure to render then and nomore the simple Login Component. – Cesare Polonara Apr 04 '22 at 00:29
  • function withNavigate = Component => props => { this line first = mark get '(' expected error, also LoginwithNavigate function can added to the app.js folder ? or only can added to the Login ? – Bavindu Dissanayake Apr 04 '22 at 00:48
  • Sorry there was a syntax mistake, corrected ( replaced function with const ). LoginWithNavigate is a React Component, and you will use it inside the return of a render method of a React Component in JSX like: . Please take time to read docs on this subject to understand better what you are doing: [HOC](https://en.reactjs.org/docs/higher-order-components.html) – Cesare Polonara Apr 04 '22 at 00:53