简体   繁体   中英

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

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM