1

I have react js code below where I put semantic ui react Dropdown component in a map. yoe is an array in state, I put value={yoe[i]}, but how can I have the index i being passed to the onChange prop? I tried the following, but the method onAddYoe seems doesn't recognize i. Can someone kindly help? Thanks!

              {specialties &&
                specialties.map((specialty, i) => {
                  return (
                    <div className="a-row" key={i}>
                      <div className="a-col-md-12">
                        <div className="a-text-box">
                          <label className="a-mb-5">
                            Years of experience in {specialty}
                          </label>
                          <br />
                          <Dropdown
                            placeholder="0-1 years"
                            fluid
                            selection
                            value={yoe[i]}
                            options={this.yoeList}
                            onChange={this.onAddYoe(i)}
                          />
                          {errors.email ? (
                            <span className="error">Email Required</span>
                          ) : null}
                        </div>
                      </div>
                    </div>
                  );
                })}
1
  • What I'm seeing here is an expression that evaluates to true or false: (specialties && anArray). Can I see more of the code? Maybe a sandbox or fiddle or something? Commented Feb 8, 2020 at 5:45

1 Answer 1

1

I don't know how you defined your onAddYoe but I am suspecting it is something like this.

function onAddYoe(i) {
  // do something based on i
}

Then you are using it on onChange like so, notice that onChange expects a function but here you are actually returning the result of the function.

<
  onChange={this.onAddYoe(i)}
/>

You should change your function to return a function like so:

function onAddYoe(i) {
  return () => {
    // do something based on i
  }
}
// or a shorter version on a functional component
const onAddYoe = (i) => () => {
  // do something based on i
} 
Sign up to request clarification or add additional context in comments.

1 Comment

Wow. Thanks Aivan. You are right, I didn't pass a function to onChange.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.