Validation using Formik with Yup and React-select

Change

handleChange("year")

To

handleChange("year")(selectedOption.value);

Currently the year field in the Formik value isn't updated. The handleChange() function returns a new function that can be called with a value to update the Formik state.

Easiest way to spot these things is by outputting the Formik props with the following code:

<pre>{JSON.stringify(props, null, 2)}</pre>

See this sandbox for an example. In the sandbox I have completely removed the need for the custom year state. I'd recommend using only the Formik state to manipulate the values. Using only Formik state you will probably have to extract only the year part when saving, because react-select uses the complete object by default.


You need to fool Formik into considering this as an event. handleChange here is from Formik. This also works for any other input field type such as react-color, or datepicker.

validationSchema = yup.object({
  year_value: yup.object().required('Year value is required.')
})
<Select 
  className=""
  name="year_value"
  id="year_value"
  placeholder='Choose year value'
  value={values.year_value}
  onBlur={handleBlur}
  onChange={selectedOption => {
    let event = {target: {name: 'year_value', value: selectedOption}}
    handleChange(event)
  }}
  onBlur={() => {
    handleBlur({target: {name: 'year_value'}});
  }}
  options={yearOptions}
/>