I have a functional component that has form. Onsubmit call I would like to redirect to another page.
function ProfileForm(props) {
// many code removed
const onSubmit = (data, e) => {
e.target.reset();
history.push({
pathname: "/OnSubmit",
state: {
response: messageFromServer
}
}
}
// many code removed
}
I got this erro:-
Unexpected use of 'history' no-restricted-globals
After Googling the error I found a similar kind of answer for location. Answer was:
Try adding window before location (i.e. window.location).
So I tried:-
window.history.push({
pathname: "/OnSubmit",
state: {
response: messageFromServer
}
}
got new error:-
Unhandled Rejection (TypeError): window.history.push is not a function
All we need to do is to call the useHistory hook inside a functional component: import { useHistory } from 'react-router-dom'; const App = () => { const history = useHistory(); const redirect = () => { history. push('/login'); } return ( <div> <h1>Hi there!
“useHistory()” hook returns the history instance created by React Router, and history. push(“/profile/John”) adds the given URL to the history stack which results in redirecting the user to the given URL path. Similarly, you can use other methods and parameters of the history object as per your need.
I think you handle routing with react-router
. If so, you need to use the history object which is passed through the ReactRouterContext
.
To do that, you need to use useHistory
hook to get the history
object.
// ...
import { useHistory } from "react-router";
// ...
function ProfileForm(props) {
const history = useHistory();
const onSubmit = (data, e) => {
e.target.reset();
history.push({
pathname: "/OnSubmit",
state: {
response: messageFromServer
}
});
}
}
Instead of history.push
try to use navigate
import { useNavigate } from 'react-router-dom';
const addToCartHandler = () => {
navigate(`/cart/${productId}?qty=${qty}`)
};
Use props.history Instead
const onSubmit = (data, e) => {
e.target.reset();
props.history.push("/OnSubmit")
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With