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
CodePudding user response:
Couple of things you need to have:
- 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>
);
}
- Use the
useHistory
hook to accesshistory.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')
}
CodePudding user response:
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')