Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot read property 'type' of undefined while using react-select with formik

I'm building a form with an auto filling text box using react-select and formik.

<Formik
    initialValues={{
        assignedTo: task.assignedTo,
    }}
    onSubmit={(values) => {
        const updatedTask = { ...task, ...values };
        editTask(updatedTask);
    }}
    render={({ handleSubmit, handleChange, values }) => (
        <form>
            <Select type="text" name="assignedTo" options={options} onChange={handleChange} value={{ value: task.assignedTo, label: task.assignedTo }} />
        </form>
    })
/>

It throws an error Cannot read property 'type' of undefined enter image description here

How to fix this and handle react-select in formik?

like image 625
Dani Vijay Avatar asked Jul 25 '18 12:07

Dani Vijay


1 Answers

the first parameter of React-Select's onChange is an option value while the first parameter of formik's handleChange is an event

React-Select: onChange(value, action) => void
Formik: handleChange(e: React.ChangeEvent<any>) => void

That is the reason why you received this kind of error.

Here is my approach. I hope this helps you.

import React from 'react';
import { Formik, Form, Field } from 'formik';
import Select from 'react-select';

function SelectField(FieldProps) {
  return (
    <Select
      options={FieldProps.options}
      {...FieldProps.field}
      onChange={option => FieldProps.form.setFieldValue(FieldProps.field.name, option)}
    />
  )
}

export default function FormikReactSelect(props) {
  const options = [
    { value: '1', label: 'White' },
    { value: '2', label: 'Yellow' },
  ];
  return (
    <Formik>
      {formProps => (
        <Form>
          <Field name='SelectColor' options={options} component={SelectField}/>
        </Form>
      )}
    </Formik>
  );
}
like image 84
Tatsu Avatar answered Sep 20 '22 15:09

Tatsu