Fernando
Fernando

Reputation: 77

Submit on clicking a radio input on react-hook-form

I'm using react-hook-form and I have to create a radio buttons form that submits when clicking an option. This is the code

const Form0 = () => {
  const { register, handleSubmit } = useForm();

  const submitFunction = (data) => {
    console.log("submitted:", data);
  };

  return (
    <form onSubmit={handleSubmit(submitFunction)}>
      <label>
        <input type="radio" value="foo" {...register("radio-button")} />
        foo
      </label>

      <label>
        <input type="radio" value="bar" {...register("radio-button")} />
        bar
      </label>

      <label>
        <input type="radio" value="foobar" {...register("radio-button")} />
        foobar
      </label>
    </form>
  );
};

I tried adding onClick={() => handleSubmit(submitFunction)} on each label but didn't work. Also I tried changing all the input types to type="submit", but when clicking an input always submit the value of the first input.

I created a sandbox https://codesandbox.io/s/react-hook-form-radio-p4p9o9

Thanks in advance

Upvotes: 1

Views: 836

Answers (1)

tpliakas
tpliakas

Reputation: 1129

One solution would be to add a ref in your form tag and use this to dispatch the submit event from your radio buttons.

Add the ref:

const formRef = React.useRef(null);


<form ref={formRef} ...

Add the onClick to your radio buttons:

onClick={handleRadioButtonClick}

and dispatch the submit event:

const handleRadioButtonClick = () => {
    formRef.current.dispatchEvent(new Event("submit", { cancelable: true }));
};

EDIT:

For you sandbox example, you can use watch and subscribe to the changes like:

  useEffect(() => {
    const subscription = watch(handleSubmit(submitFunction));
    return () => subscription.unsubscribe();
  }, [handleSubmit, watch]);

Upvotes: 1

Related Questions