4
votes

Problem:

I have select input in my Formik form in react. My code is following

<select
    className="form-control offence-select"
    id="exampleFormControlSelect1"
    value={props.values.offenceId}
    onChange={props.handleChange("offenceId")}
    onBlur={props.handleBlur("offenceId")}
 >
     <option value={0}>Select Offence</option>
         {this.renderOption()}
 </select>

What I want is I want to call two functions inside onChange , one function is formik props.handleChange and the next one is custom state update.

I did something like this.

onChange={e=>{props.handleChange("offenceId");this.handleOffence(props.values.offenceId)}}

But it only calls the second custom function but it is not changing the field value of the select. I tried a lot to find out a solution to this problem but I was unable to do so. Can someone help me to solve this issue by correcting the way I am calling function? Thank you.

2
By the looks of it I'm guessing props.handleChange is a function which returns a function. So when calling it manually in the onChange handler, shouldn't it be something like {e=>{props.handleChange("offenceId")(e.target.value);}?Jayce444

2 Answers

9
votes

You'll have to pass the event too, otherwise your callbacks do not know what the new value is. I also wouldn't count on props.values having the new value immediately, that's why I would pass the value from event in the second function call.

<select
    className="form-control offence-select"
    id="exampleFormControlSelect1"
    value={props.values.offenceId}
    onChange={(e) => {
      props.handleChange("offenceId")(e);
      this.handleOffence(e.currentTarget.value);
    }}
    onBlur={props.handleBlur("offenceId")}
 >
     <option value={0}>Select Offence</option>
         {this.renderOption()}
 </select>

You could also give your select input a name as follows, which simplifies the callback calls:

<select
    name="offenceId"
    className="form-control offence-select"
    id="exampleFormControlSelect1"
    value={props.values.offenceId}
    onChange={(e) => {
      props.handleChange(e);
      this.handleOffence(e.currentTarget.value);
    }}
    onBlur={props.handleBlur}
 >
     <option value={0}>Select Offence</option>
         {this.renderOption()}
 </select>
1
votes

Try like:

<select
    className="form-control offence-select"
    id="exampleFormControlSelect1"
    value={props.values.offenceId}
    onChange={() => {
      props.handleChange("offenceId");
      this.handleOffence(props.values.offenceId);
    }}
    onBlur={props.handleBlur("offenceId")}
 >
     <option value={0}>Select Offence</option>
         {this.renderOption()}
 </select>