-
-
Save chancesmith/afa082d291db54360589f882f04be6b9 to your computer and use it in GitHub Desktop.
Use react-select with Formik
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const options = [ | |
{ value: 'foo', label: 'Foo' }, | |
{ value: 'bar', label: 'Bar' }, | |
] | |
return <Field name={'example'} component={SelectField} options={options} placeholder="Select something" /> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {FieldProps} from 'formik'; | |
import React from 'react'; | |
import Select, {OptionsType, ValueType} from 'react-select'; | |
interface Option { | |
label: string; | |
value: string; | |
} | |
interface CustomSelectProps extends FieldProps { | |
options: OptionsType<Option>; | |
isMulti?: boolean; | |
placeholder: string; | |
} | |
export const SelectField = ({field, form, options, isMulti = false, placeholder}: CustomSelectProps) => { | |
const onChange = (option: ValueType<Option | Option[]>) => { | |
form.setFieldValue( | |
field.name, | |
isMulti ? (option as Option[]).map((item: Option) => item.value) : (option as Option).value, | |
); | |
}; | |
const getValue = () => { | |
if (options) { | |
return isMulti | |
? options.filter(option => field.value.indexOf(option.value) >= 0) | |
: options.find(option => option.value === field.value); | |
} else { | |
return isMulti ? [] : ('' as any); | |
} | |
}; | |
return ( | |
<Select | |
name={field.name} | |
placeholder={placeholder} | |
value={getValue()} | |
onChange={onChange} | |
options={options} | |
isMulti={isMulti} | |
/> | |
); | |
}; | |
export default SelectField; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment