Ben
Ben

Reputation: 10298

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!

Upvotes: 1

Views: 5628

Answers (3)

taggartJ
taggartJ

Reputation: 287

Another way to do it dynamic is give it a value callback this works well if pre populating the "value" from some var.

/* Better function for larger forms */
handleChange = (event) =>  {
    var name = event.target.name;
    var value =  event.target.value;
    this.setState({[name]: value});
}
/* set Default and callback to state */
valueCallback = (value, name) => {
    if (this.state[name]) {
        return this.state[name]
    }
    else {
        return value;
    }
}

then you can go ...

 var defaut = '1234'; // or this.props.something.something;

 <input type={type} name={name} value={this.valueCallback(defaut, name)}  onChange={this.handleChange} />

Upvotes: 0

Tom Fenech
Tom Fenech

Reputation: 74695

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

Upvotes: 4

Piotr Sołtysiak
Piotr Sołtysiak

Reputation: 1006

<input value={this.state.value} onKeyDown={this.props.changeCallback.bind( this, this.state.value)} ></input>

Would do the job.

Upvotes: 1

Related Questions