3

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)} />

3 Answers 3

7

You can use curried function to implement that.

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

...

<input defaultValue={name} onChange={this.onChange(index,iamstring)} />
Sign up to request clarification or add additional context in comments.

Comments

2

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)} />

Comments

1

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).

Comments

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.