Returning correct value using react-select and react-hook-form

geeberry picture geeberry · Jul 8, 2020 · Viewed 10k times · Source

I'm using react-hook-forms Controller api around AsyncSelect from react-select to load options as the user types from an external API. Everything works fine except the returned value is coming back as the string "[object Object]" instead of the fullName property from the object.

My component:

           <Controller
            control={control}
            name="businessCategory"
            as={
              <AsyncSelect
                className="react-select-container"
                loadOptions={v => handleAutocompleteLookup(v)}
                onChange={handleCategoryInputChange}
                getOptionLabel={option => option.name}
                getOptionValue={option => option.fullName}
              />
            }
          />

My handleChange function. SetValue is from react-hook-form:

  const handleCategoryInputChange = newValue => {
    return setValue('businessCategory', newValue, true);
  };

Any my data is an array of objects with the following shape:

{
  fullName: "DJ service"
  id: "gcid:dj"
  name: "DJ service"
  publisher: "GMB"
}

Any clues on this would be appreciated, thank you!

Answer

Malay M picture Malay M · Mar 3, 2021

Update your code in following way

In your import

import { useForm, Controller } from 'react-hook-form';
import Select from 'react-select';

In your hook component

function Yourcomponent(props){

    const methods = useForm();
    const { handleSubmit } = methods;
    

    const options = [
     { value: '1', label: 'Apple'},
     { value: '2', label: 'Ball'},
     { value: '3', label: 'Cat'},
    ];
    
    const default_value = 1; // you can replace with your default value
    

    // other codes of the component 
    

    function submitHandler(formData){
    
    // values are available in formData

    }


    return(
      <div>
        
        {* other part of your component *}
        <form onSubmit={handleSubmit(submitHandler)} >

           {* other part of your form *}
            <Controller
                control={methods.control}
                defaultValue={default_value}
                name="field_name_product"
                render={({ onChange, value, name, ref }) => (
                    <Select
                        inputRef={ref}
                        classNamePrefix="addl-class"
                        options={options}
                        value={options.find(c => c.value === value)}
                        onChange={val => onChange(val.value)}
                    />
                )}
            />

           {* other part of your form *}
        </form>

        {* other part of your component *}
      </div>
    )
}