Skip to content

Instantly share code, notes, and snippets.

@hubgit
Last active July 16, 2024 07:40
Show Gist options
  • Save hubgit/e394e9be07d95cd5e774989178139ae8 to your computer and use it in GitHub Desktop.
Save hubgit/e394e9be07d95cd5e774989178139ae8 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} />
import { FieldProps } from 'formik'
import React from 'react'
import Select, { Option, ReactSelectProps } from 'react-select'
export const SelectField: React.SFC<ReactSelectProps & FieldProps> = ({
options,
field,
form,
}) => (
<Select
options={options}
name={field.name}
value={options ? options.find(option => option.value === field.value) : ''}
onChange={(option: Option) => form.setFieldValue(field.name, option.value)}
onBlur={field.onBlur}
/>
)
@rever96
Copy link

rever96 commented Aug 11, 2023

@alexluongfm with your versions still gives Generic type 'Options' requires 1 type argument(s). error on line 6

"react-select": "^5.7.4",

@IlyaZha
Copy link

IlyaZha commented Sep 22, 2023

My Solution for react-select@^5.7.4:

export default function MultipleSelect({ fieldName, placeholder, ...props }) {
  const [field, meta, { setValue }] = useField(fieldName);
  const options = props.children.map((option) => ({
    value: option.props.value,
    label: option.props.children,
  }));

  const onChange = (selectedOptions: MultiValue<any>) => {
    setValue(selectedOptions);
  }

  return (<>
    <Select
      isMulti={true}
      defaultValue={options.find((option) => option.value === field.value)}
      placeholder={placeholder}
      onChange={onChange}
      options={options}
      onBlur={field.onBlur}
    />
  </>);
}

Form of select should be wrapped with <Formik></Formik>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment