Dinith Minura
Dinith Minura

Reputation: 1496

Pass additional params to onSelect method of React Ant Design Select component

I need to pass an additional param to onSelect method of AntD Select component which cannot be listed in the options object array. I'm trying to render several Select components on the UI by mapping an array and need to pass the index of the rendered element into onSelect method. According to the documentation, it supports only read value and options from the onSelect method. Any solution for this?

Current Code:

list.map(input, index) -> {
  return <Select 
          .....
          onChange={handleOnChange}
          />
}

handelOnChange = (value, options) => {
  .....
}

Expected Code:

list.map(input, index) -> {
  return <Select 
          .....
          onChange={handleOnChange(index)}
          />
}

Upvotes: 2

Views: 4421

Answers (2)

Subrato Pattanaik
Subrato Pattanaik

Reputation: 6049

I am adding some explanation to @Babak answers.

In your current code, you are passing an event handler (handleOnChange) to the onChange onEvent attribute of the Select component.

<Select 
     .....
     onChange={handleOnChange}
 />

When the onChange event happens it will then call the function handleOnChange with the event as default parameter and other parameter

In your expected code, you are passing the result of the handleOnChange(index) function (because of parenthesis we are saying it make a function call and the result is passed to the onChange attribute), but this is not our intention. We have to pass the event handler to onChange attribute not the result of it. That is the golden rule of the event handler in REACT.

If you want to pass arguments other than the event argument then you need to do:

<Select 
   ....
   onChange={(value, options) => handleOnChange(value, options, index)}
 />

Here you can see that we are passing a callback function. Note that in the above snippet we cannot access the event inside the handleOnChange. If you want to have an event in the event handler along with other parameters you can do like this:

<Select 
    .....
   onChange={(event, value, options) => handleOnChange(event, value, options, index)}
/>

Some valid event handlers:

<button onClick={handleClick} /> // valid and can access event
<button onClick={() => handleClick()} /> // valid and access event
<button onClick={(event) => handleClick(event, name)} /> // valid and access event and other parameters

Upvotes: 3

Babak Yaghoobi
Babak Yaghoobi

Reputation: 1985

Expected Code:

list.map(input, index) -> {
  return <Select 
          .....
          onChange={(value, options)=>handleOnChange(value, options, index)}
          />
}

Upvotes: 5

Related Questions