skip to Main Content

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


  1. 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 the handleSubmit function that handles form submissions. You can pass your onSubmit function as an argument to handleSubmit. Here’s an updated version of your code:

    import { useForm } from 'react-hook-form';
    import { useHistory } from 'react-router-dom';
    
    const YourComponent = () => {
      const history = useHistory();
      const { register, handleSubmit, formState: { isValid } } = useForm();
    
      const onSubmit = async (data) => {
        history.push("/Page2");
      };
    
      return (
        <form onSubmit={handleSubmit(onSubmit)}>
          <Input 
            {...register("name")} 
            inputProps={{maxLength: name.maxLength}}
          />
          <Button
            variant="cta"
            type="submit"
            disabled={!isValid}
          >
            Continue
          </Button>
        </form>
      );
    };
    

    In this code, the handleSubmit function from useForm handles form submissions and calls your onSubmit function when the form is valid. By removing the event parameter and event.preventDefault(), you can rely on the built-in form handling provided by useForm. The history.push("/Page2") line will trigger the redirection to the desired /Page2 route.

    Make sure you have the appropriate dependencies installed (react-router-dom and react-hook-form) and imported into your component.

    Login or Signup to reply.
  2. 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:

    import { useHistory } from 'react-router-dom';
    
    const ComponentName = () => {
      const history = useHistory();
      
      const onSubmit = async (data) => {
        history.push("/Page2");
      };
    
      return (
        <form onSubmit={handleSubmit(onSubmit, onError)}>
          <Input 
            {...register("name")} 
            inputProps={{maxLength: name.maxLength}}
          />
          <Button
            variant="cta"
            type="submit"
            disabled={!isValid}
          >
            Continue
          </Button>
        </form>
      );
    };
    
    

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search