Reputation: 4719
I have this functional component.
import { useHistory } from "react-router-dom";
function ProfileForm(props) {
const form = useForm();
const {
register,
handleSubmit,
errors
} = form;
const history = useHistory(); // TypeError: Cannot read property 'history' of undefined
......
}
Why this error? Btw, I installed react-router-dom. How to use history in the functional components?
Update more code:-
axios.post('http://localhost:8080/profile', profile)
.then(res => {
history.push({
pathname: "/OnSubmit",
state: {
response: res.data,
msgVariant: "success"
}
})
}).catch((error) => {
// handle this error
history.push({
pathname: "/OnSubmit",
state: {
response: error.message,
msgVariant: "danger"
}
})
})
Later I am using history as above?
Upvotes: 2
Views: 49
Reputation: 3411
Be it a functional component or a class component, for router history to work the component must be a child of the Router component.
We need to do something like this,
import {
BrowserRouter as Router
} from "react-router-dom"
//and then, wherever we want to use `history`, we need to have it nested under this <Router />
<Router>
<SomeOtherComponent>
...
<ComponentWhereWeWantToUseHistory />
...
</SomeOtherComponent>
</Router>
I hope it helps. Happy coding :)
Upvotes: 2