Reputation: 331
I am trying to use react-select (with multi-values) with Formik but unsure how to reflect values selected within my Formiks initialStates values.
I have the following:
import Select from 'react-select';
const myOptions= [
{ value: 'Food', label: 'Food' },
{ value: 'Being Fabulous', label: 'Being Fabulous' },
{ value: 'Unicorns', label: 'Unicorns' },
{ value: 'Kittens', label: 'Kittens' },
];
"props": {
"myGroups": [
{
"myGroupName": "",
"selectedOptions": []
}
]
}
<Select
options={myOptions}
isMulti={true}
name={`myGroups.${index}.selectedOptions`}
/>
I am able to populate the react-select list correctly but unsure what I need to do with setting: myGroups.${index}.selectedOptions
to hold the values like:
"selectedOptions": [
"Food",
"Kittens"
]
I'm assuming I will need an onChange
function call and with Formik, will also need to use setFieldValue
Any help would be great.
Upvotes: 0
Views: 1308
Reputation: 330
I have previously worked on this library and required to do the exact same thing as you do.
Just add an onChange
event. Then, have a variable e
that will match with handleChange
event from Formik
.
<Formik initialValues={initialFormValues} validationSchema={formSchema} onSubmit={this.handleFormSubmit} enableReinitialize>
{({ handleSubmit, handleChange }) => (
<Form noValidate onSubmit={handleSubmit} autoComplete='off'>
<Select
options={myOptions}
isMulti={true}
name={`myGroups.${index}.selectedOptions`}
onChange={(selectedOption) => {
let e = { target: { name: `myGroups.${index}.selectedOptions`, value: selectedOption } };
handleChange(e);
}}
/>
</Form>
)}
</Formik>
Upvotes: 1