React multi-step form using react-select not updating state

292 Views Asked by At

I'm creating a multi-step form using React and one of the steps uses react-select.

The parent component has the following change handler:

const handleChange = input => e => {
    setFormData({ ...formData, [input]: e.target.value});
  }

It works fine for the majority of my fields and steps but it seems this isn't usable for react-select due to react-select returning an object. So I wrote a separate handler in the parent component as follows:

const handleSelectChange = e => {
    setFormData({ ...formData, [input]: e });
  } 

And in the Select component I have the following:

<Select
   defaultValue={values.purpose}
   name="purpose"
   options={purposeOptions}
   className="basic-single"
   classNamePrefix="select"
   onChange={handleSelectChange('purpose')}
/>

However I get the error that 'handleSelectChange' is not a function. I have tried changing the handler code to this:

const handleSelectChange = e => {
        setFormData({ ...formData, purpose: e });
      } 

and removing the parentheses in the Select component so onChange now reads:

onChange={handleSelectChange}

This has removed the error but now the stateField is not updating with the value from the select.

Any advice will be much appreciated.

1

There are 1 best solutions below

1
On

Change onChange={handleSelectChange('purpose')} to

onChange={() => handleSelectChange('purpose')}