1

I want to navigate from one page to another in ReactJS I am using history.push but it gives me an error that TypeError: Cannot read properties of undefined (reading 'push') at Login.jsx:65 at async loginHandel (Login.jsx:51)

This is my App.js code

import React from "react";
import "bootstrap/dist/css/bootstrap.min.css";
import Login from "./components/Login";

function App() {
  return (
    <div className="App">
      <Login />
    </div>
  );
}

export default App;

and this is my login.jsx function code

  const loginHandel = async () => {
    setLoading(true);
    const data = await axios
      .get(
        `http://116.202.231.219:8069/Restaurant/Login_Updated?Cont4=${email}&Pswd=${password}`
      )
      .then((res) => {
        //check the res if its getting the correct data or not?
        //restructure accordingly
        console.log(res);
        const persons = res;
        if (persons.status === 200) {
          //perform any thing here
          alert("It is working");
          // setUser(persons);
          setLoading(false);
          history.push("/dashboard");
          // window.open("./Dashboard.jsx")
          
        }
      })
      .catch((err) => {
        //handel your error
        console.log(err);
        alert("User email and passwoed mismatched!");
        // setLoading(false);
      });
  };

I want that after the API success it should navigate me to the dashboard page but it does not and it gives the alert of it is working and also gives the alert of User email and passwoed mismatched I would really appreciate it if any of you could help me sort this problem

  • Can you make a simple search before make ask? [check this post](https://stackoverflow.com/questions/37295377/how-to-navigate-from-one-page-to-another-in-react-js) – naxsi Sep 22 '21 at 14:31

3 Answers3

4

Couple of things you need to have:

  1. Router for your base (Check here for better understanding)
import {BrowserRouter as Router, Switch, Route} from 'react-router-dom'

function App() {
  return (
    <div className="App">
      <Router>
         <Switch>
           <Route path='/' component={/* Import and use your component */} />
         </Switch>
      </Router>
    </div>
  );
}

  1. Use the useHistory hook to access history.push (This will be true for the components who are rendered under <Router>)
import {useHistory} from 'react-router-dom'

const YourFunctionComponent = props => {

  const history = useHistory()
  
  const letsChangeLocation = () => history.push('/wherever')
}

Sinan Yaman
  • 5,714
  • 2
  • 15
  • 35
0

you need to import useHistory in your component. then use it to navigate.

import { useHistory } from "react-router-dom";

// in component

const history = useHistory();
history.push('/url')
Asad Gulzar
  • 403
  • 4
  • 8
0
  1. Define Routes in main base file.

  2. use useHistory for react router version 5

    import { useHistory } from "react-router-dom";
    
    function HomeButton() {
      let history = useHistory();
    
      function handleClick() {
        history.push("/home");
      }
    
      return (
        <button type="button" onClick={handleClick}>
          Go home
        </button>
      );
    }
    

    use useNavigate, for react router version 6

    import { useNavigate } from "react-router-dom";
    
    function SignupForm() {
      let navigate = useNavigate();
    
      async function handleSubmit(event) {
        event.preventDefault();
        await submitForm(event.target);
        navigate("../success", { replace: true });
      }
    
      return <form onSubmit={handleSubmit}>{/* ... */}</form>;
    }
    
Sahil Thummar
  • 1,926
  • 16
  • 16