0
votes

i'm entirely lost when it comes to figuring this out. I have a existing select that works with formik & react-select, but I can't get it to work as a multi. Here's what i have so far:

import Select from 'react-select';
import { useField } from 'formik';

export default function SelectField(props) {
  const [field, state, { setValue, setTouched }] = useField(props.field.name);

  const onChange = ({ value }) => {
    setValue(value);
  };

  return <Select {...props} onChange={onChange} onBlur={setTouched} />;
}

and

 <Field
     component={SelectField}
      name="campfeatures"
      options={selectObjects}
            />

How would I turn this into being capable of taking multi select? If I add isMulti to the Field, it "works" but it doesn't actually retain the multiple values.

Thanks for your help!

1

1 Answers

1
votes

The argument type for onChange changes when the react-select receives isMulti from a single object to a list of objects. When using isMulti you don't need to destruct; the first parameter is the value.

You also want to make the react-select a controlled component by managing its value.

export default function SelectField(props) {
  const [field, state, { setValue, setTouched }] = useField(props.field.name);
  
  // value is an array now
  const onChange = (value) => {
    setValue(value);
  };

 // use value to make this a  controlled component
 // now when the form receives a value for 'campfeatures' it will populate as expected
  return <Select {...props} value={state?.value} isMulti onChange={onChange} onBlur={setTouched} />;
}

The new value is an array of the selected options with label and value fields. If you want to store just the value you'll need to map it to a value and modify the react-select to handle that