author avatar

rishav.raj

Thu Oct 05 2023

I've have a radio input in a React Hook form and attempted to pass a boolean value, however when i submit the form, i receive the typeof value as a string. Knowing that RHF has valueAsNumber to convert it as number. I thought that setValueAs was a generic way to allow any conversion but I can't make it work.

I learn how to extract a boolean value from a RHF radio input.

The setValueAs approach, which I have previously tried, only functions with text input (such as type="text" or type="number"). Even if the value for a radio button is a string, it doesn't function.

In order to fix it, a Controller component can be used.

Solution:-

      <Controller
            defaultValue={false}
            control={control}
            name="booking_for_someone"
            render={({ field: { onChange, onBlur, value, ref } }) => (
              <label className="booking-for-someone">
                <span className="f-semibold">{t("I'm Booking For")}</span>
                <div>
                  <input
                    type="radio"
                    onBlur={onBlur}
                    onChange={() => onChange(false)}
                    checked={value === false}
                    inputRef={ref}
                    id="myself"
                  />
                  <label
                    htmlFor="myself"
                   >
                    {t("Myself")}
                  </label>
                </div>
                <div >
                  <input
                    type="radio"
                    className="w-16 h-16 rounded-full accent-blue"
                    onBlur={onBlur}
                    onChange={() => onChange(true)}
                    checked={value === true}
                    inputRef={ref}
                    id="someone-else"
                  />
                  <label
                    htmlFor="someone-else"
                   >
                    {t("Someone Else")}
                  </label>
                </div>
              </label>
            )}
          />

Thanks :slightly_smiling_face: