'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>
Solution 1:[1]
You need to wrap the controlled components with Controller
.
<Controller
control={control}
name="test"
render={({
field: { onChange, onBlur, value, name, ref },
fieldState: { invalid, isTouched, isDirty, error },
formState,
}) => (
<Checkbox
onBlur={onBlur} // notify when input is touched
onChange={onChange} // send value to hook form
checked={value}
inputRef={ref}
/>
)}
/>
You can read more on the official docs: https://react-hook-form.com/api/usecontroller/controller/
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | ilkerkaran |