integrate react-select with formik

PHOTO EMBED

Mon Apr 03 2023 07:31:24 GMT+0000 (Coordinated Universal Time)

Saved by @nimaSm #formik #react-select

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}
  />
content_copyCOPY