Ben Ben - 17 days ago 9
React JSX Question

In React, how do I pass input value to callback function?

I'd like to call some callback in a React component whenever the input's value has changed.

simplified example should explain:

in a

jsx
file:

<input onKeyDown={this.props.changeCallback( VALUE_OF_INPUT )} ></input>


what should
VALUE_OF_INPUT
be?

Thanks!

Answer

There's not much React-specific about this. Use the event which is passed to the callback as the first argument:

onKeyDown={event => this.props.changeCallback(event.target.value)}

This approach (using a fat arrow function) also handles binding this, at the expense of creating a new anonymous function once per render. Note that calling bind essentially does the same thing, so this is my preferred option out of the two.

It's important to make the distinction between assigning a function to the onKeyDown attribute (as is done here) and calling the function (what you did).

Comments