How can I get option value from react select?

Viewed 737

My codes are as below, can you help me? Where am I doing wrong?

const options = [
    { value: 'chocolate', label: 'Chocolate' },
    { value: 'strawberry', label: 'Strawberry' },
    { value: 'vanilla', label: 'Vanilla' }
]

const { register, handleSubmit, watch, formState: { errors }, control } = useForm();
const onSubmit = (data, e) => {
    e.preventDefault();
    console.log(data);
}

I want to get the option data using react select, but the defaltvalue is coming, I can't get the option data at all.

 <Controller
    name='stocktype'
    render={({ register, value }) => (
        <Select
            {...register}
            options={options}
            styles={customStyles}
            noOptionsMessage={() => 'Aramanıza uygun değer bulunamadı'}
            placeholder={'Stok Tipi Seçiniz'}
            value={options.find((c) => c.value === value)}
        />
    )}
    control={control}
    defaultValue={options[0]}
    
/>
1 Answers

You'll need to grab the controller's hooks and pass them to the Select component in order to execute the correct events to grab the data.

Do something like this:

<Controller
  control={control}
  name="test"
  render={({
    field: { onChange, onBlur, value, name, ref },
    register
  }) => (
    <Select
      {...register}
      options={options}
      styles={customStyles}
      noOptionsMessage={() => 'Aramanıza uygun değer bulunamadı'}
      placeholder={'Stok Tipi Seçiniz'}
      value={value}
      onChange={onChange} // send value to hook form
      onBlur={onBlur} // notify when input is touched
    />
  )}
/>

Notice the field attribute under render and how hooks are passed to the Select.

Related