How to receive select value in handlesubmit function with formik react js?

Ahmad picture Ahmad · May 15, 2018 · Viewed 21.6k times · Source

i am developing a form in reactjs using formik plugin plugin link. when i submit form i am getting text fields values but dropdown values are coming empty...

this is my dropdown select

<div className="form-group">                  
                <Field component="select" id="category" name="category" value={this.state.value} className={"form-control"} onChange={ this.handleChange }>
                   <option value="lokaler">Lokaler</option>
                   <option value="jobb">Jobb</option>
                   <option value="saker-ting">Saker & ting</option>
                   <option value="evenemang">Evenemang</option>
                </Field>
                  </div>

handle submit function

export default withFormik({
  enableReinitialize: true,
  mapPropsToValues({ category }) {
    return {      
      category: category || ''
    }
  },
    handleSubmit(values, { setStatus, setErrors }){
      console.log("data is this: "); 
      console.log(values); //here i am getting all form fields values except select value returning empty value
      console.log("category: "+values.category);// here i always get empty value but not getting selected value

      }

i am getting all text fields values in handle submit function but i am not able to get dropdown selected value....kindly tell me how to get dropdown select value in handle submit function ?

Answer

Tun Tun Aung picture Tun Tun Aung · Jun 25, 2018

I also faced this problem yesterday. My problem was to submit form that contains ant design dropdown. I finally make it work after hours of:

The doc said you need to set onChange, onBlur events to setFieldValue, setFieldTouched props respectively like 3rd-party input example:

<MySelect
    value={values.topics}
    onChange={setFieldValue}
    onBlur={setFieldTouched}
    error={errors.topics}
    touched={touched.topics}
/>

So to my problem, I need to change a bit:

<Select
  {...field}
  onChange={(value) => setFieldValue('fruitName', value)}
  onBlur={()=> setFieldTouched('fruitName', true)}
  value={values.fruitName}
  ...
>
...
</Select>

Hope this will help.

Here is my CodeSandbox