jetski
jetski

Reputation: 187

How to pass additional parameters to onChange function in React

So, I've faced this problem: I have this type of Element here, obviously there's event when changing the input, is it possible to pass params like this and access event as well? if so, how could I do it?

// this function accepts two other params index, stringValue
function onChange(index ,stringValue) {
    console.log(event.target.value);
    console.log("index?: " + index + " and value" + stringValue)
}

//this input is in Child Component
const index = 69;
const someRandomValue='iamstring';
<input defaultValue={name} onChange={onChange(index,iamstring)} />

Upvotes: 3

Views: 8637

Answers (3)

Flagship1442
Flagship1442

Reputation: 1726

If you want you can make onChange into a function that returns another function.

Then you can do something like this:

const Element = () => {
  const index = 69;
  const iamstring = 'iamstring';

  const onChange = (index, stringValue) => event => {
    console.log(event.target.value);
    console.log('index?: ' + index + ' and value' + stringValue);
  };

  return <input defaultValue={name} onChange={onChange(index, iamstring)} />;
};

Bear in mind that the input's onChange prop expects a function, so you can only execute a function inside the onChange like this if that function is returning another function. (This is called a higher order function).

Upvotes: 1

Drew Reese
Drew Reese

Reputation: 203099

You can convert the handler to a curried higher order function to return a function to be used as the callback that accepts the click event object

function onChange(index,stringValue) {
  return (event) => {
    console.log(event.target.value);
    console.log("index?: " + index + " and value" + stringValue)
  };
}

Or you can proxy the event object through to the callback, remember to add the event object as an argument to the handler

function onChange(event, index ,stringValue) {
    console.log(event.target.value);
    console.log("index?: " + index + " and value" + stringValue)
}

<input defaultValue={name} onChange={e => onChange(e, index, iamstring)} />

Upvotes: 2

Thunderbolt Engineer
Thunderbolt Engineer

Reputation: 1563

You can use curried function to implement that.

onChange = (index, stringValue) => (event) => {
...
}

...

<input defaultValue={name} onChange={this.onChange(index,iamstring)} />

Upvotes: 7

Related Questions