I have a formik form, when I click on the submit button, I want the user to be redirected to /. But it doesn’t work, nothing happens. I don’t think it is useful to past here the code of the component, here is just the React Router route.
<Route exact path = "/create"
element = {
<DepenseForm
onSubmit = {(depense) => {
console.log("1");
console.log("2"); this.createDepense(depense);
console.log("3"); redirect("/")
console.log("4");}
}
/>}
/>
In the console, all numbers are printed 1,2,3,4,5. The createDepense method is also executed.
But the React Router redirect method is not 🙁
No error messages, no warning.
Any clue?
Thanks
2
Answers
You need to use
redirect
function inreact-router-dom v6
like this:instead of
or you can use
useNavigate
hook.The
redirect
utility function is only validly used from Data routerloader
andaction
functions. It can’t be used in a React component. You should use theuseNavigate
hook instead and use thenavigate
function in the callback handler to issue an imperative redirect.Since it appears you are passing in a submit handler to the routed component the
useNavigate
hook will need to be called in the parent component.Example:
If the parent component is still an older React class component for some reason then you’ll need to create your own custom
withRouter
Higher Order Component to inject thenavigate
function as a prop. For more information on this see What happened to withRouter? I need it!