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
How to fix this and handle react-select in formik?
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>
);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With