import {FieldProps} from 'formik' import Select, {Options, OnChangeValue} from 'react-select' interface Option { label: string value: string } interface FormikSelectProps extends FieldProps { options: Options<Option> isMulti?: boolean isSearchable?: boolean disabled?: boolean } export const FormikSelect = ({ field, form, options, isSearchable=false, isMulti=false, disabled=false, }: FormikSelectProps) => { const onChange = (option: OnChangeValue<Option | Option[], boolean>) => { form.setFieldValue( field.name, isMulti ? (option as Option[]).map((item: Option) => item.value) : (option as Option).value ) } const getValue = () => { if (options && options.length !== 0 && field.value) { return isMulti ? options.filter((option) => field.value.indexOf(option.value) >= 0) : options.find((option) => option.value === field.value) } else if(field.value){ return isMulti ? [] : ('' as any) } } return ( <Select name={field.name} value={getValue()} onChange={onChange} options={options} isMulti={isMulti} isSearchable={isSearchable} isDisabled={disabled} /> ) } // -------------- in form component ---------------------- import { Field } from 'formik' const options = [ {value: '1', label: 'label 1'}, {value: '2', label: 'label 2'}, ] <Field name='any-name' component={FormikSelect} options={options} />
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter