Skip to content

Instantly share code, notes, and snippets.

@chancesmith
Forked from hubgit/SelectField.tsx
Created February 28, 2020 11:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chancesmith/afa082d291db54360589f882f04be6b9 to your computer and use it in GitHub Desktop.
Save chancesmith/afa082d291db54360589f882f04be6b9 to your computer and use it in GitHub Desktop.
Use react-select with Formik
const options = [
{ value: 'foo', label: 'Foo' },
{ value: 'bar', label: 'Bar' },
]
return <Field name={'example'} component={SelectField} options={options} placeholder="Select something" />
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