Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 ?

like image 807
Ahmad Avatar asked May 15 '18 06:05

Ahmad


1 Answers

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:

  • revisiting the Formik Docs
  • watch Andrew Mead's video Better React Form with Formik again.
  • also viewing Jared Palmer's Working with 3rd-party inputs #1: react-select

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

like image 142
Tun Tun Aung Avatar answered Oct 04 '22 23:10

Tun Tun Aung