With React Hook Form, I want to redirect user to /Page2 on Submit.
However, for some reason, I am getting redirected to http://localhost:3000/#/
I have event.preventDefault(), but still not sure why the redirect is happening to / and not to Page2
const onSubmit = async (data, event) => {
event.preventDefault();
history.push("/Page2"); // history = useHistory()
return false;
};
<form ref={formRef} onSubmit={handleSubmit(onSubmit, onError)}>
<Input
{...register("name")}
inputProps={{maxLength: name.maxLength}}
/>
<Button
variant="cta"
type="submit"
disabled={!isValid}>
Continue
</Button>
</form>
Also, to add, I am usinguseForm as below
const {register, handleSubmit, trigger, setValue, getValues, formState, setError, watch} = useForm({
resolver: yupResolver(mySchema),
mode: "onBlur",
defaultValues: {name: ''}
});
Also, I have the import as
import {withRouter, useHistory} from "react-router-dom"; //"react-router-dom": "5.2.0",
And my component is exported as below
export default withRouter(MyForComponent);
Is it possible without Submit. I am fine to invoke a normal function on button (can be made type normal) click and then redirect ?
2
Answers
The issue you’re facing with the redirection can be resolved by making a small adjustment to your code. Currently, you’re using
event.preventDefault()
to prevent the default form submission behavior, but it seems that the redirection is still happening to the root URL.To fix this, you can make use of the
useForm
hook from React Hook Form, which provides thehandleSubmit
function that handles form submissions. You can pass youronSubmit
function as an argument tohandleSubmit
. Here’s an updated version of your code:In this code, the
handleSubmit
function fromuseForm
handles form submissions and calls youronSubmit
function when the form is valid. By removing theevent
parameter andevent.preventDefault()
, you can rely on the built-in form handling provided byuseForm
. Thehistory.push("/Page2")
line will trigger the redirection to the desired/Page2
route.Make sure you have the appropriate dependencies installed (
react-router-dom
andreact-hook-form
) and imported into your component.You are using event.preventDefault() correctly to prevent the default form submission behavior. However, the issue might be related to the usage of return false after calling history.push("/Page2").
When using React Hook Form, you don’t need to return a boolean value from the onSubmit function. Instead, you can remove the return false statement and make the following adjustments:
By removing event as a parameter in the onSubmit function and the event.preventDefault() line, you can simplify the code. The history.push("/Page2") will redirect the user to /Page2 upon form submission.