Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use react-hook-form with select and multiselect

I'm trying to use react-hook-form with multi-select and select but it is not working. It worked with normal text field but not with select and multiselect. Here's my code. Thank you so much.

 <div className="pricing__section80">
                <div className="pricing__container-card70">
                  <MultiSelect
                    required="true"
                    labelledBy="Hora"
                    name="user_select7"
                    value={options.filter((obj) => date1.includes(obj.value))}
                    onChange={handleChange}
                    options={options}
                    {...register("user_select7", { required: true })}
                  />
                  {errors.user_select7 && <h7>Porfavor llena este campo</h7>}
                </div>
              </div>
              <div className="pricing__section80">
                <div className="pricing__container-card77">
                  <Select
                    placeholder="Metodo de pago"
                    name="user_cash"
                    value={cash}
                    onChange={setCash}
                    options={options6}
                    {...register("user_cash", { required: true })}
                  />
                  {errors.user_cash && <h7>Porfavor llena este campo</h7>}
                </div>
              </div>
like image 967
Andres Pelaez Avatar asked Aug 04 '26 22:08

Andres Pelaez


1 Answers

I had the same issue, I implemented react-select with useForm hook this way:

import Select from 'react-select';

// ... more code

const {
    formState: { errors },
    handleSubmit,
    register,
    control,
    watch
} = useForm({
    defaultValues: {}
});

// ... more code

<Controller
    control={control}
    name="categories"
    render={({
        field: { onChange, onBlur, value, name, ref },
    }) => (
        <Select
            options={options}
            isLoading={isLoading}
            onChange={onChange}
            isMulti={true}
            onBlur={onBlur}
            value={value}
            name={name}
            ref={ref}
        />
    )}
/>

// ... more code
like image 127
anayarojo Avatar answered Aug 08 '26 14:08

anayarojo