Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass multiple parameters to input's onChange handler

I render collection of input elements for objects in array.

render: function() {
    var ranges = [];
    this.props.ranges.map(function(range, index) {
        var rangeElement = <Input type="text"
            value={range.name} onChange={this.changeRangeName.bind(this)} />
        ranges.push(rangeElement);
    }, this);

    // render ranges
}

this allows me to write onChange handler function:

changeRangeName: function (event) {
    var newName = event.target.value;
},

but in this handler I need id of range object I want to change. So I could change change how I create input elements in render function and change:

var rangeElement = <Input type="text"
            value={range.name}
            onChange={this.changeRangeName.bind(this, range.id)} />

Now my handler will receive range.id as parameter but now I don't have the newName value. I can get it using refs

var rangeElement = <Input type="text"
            ref={'range' + range.id}
            value={range.name}
            onChange={this.changeRangeName.bind(this, range.id)} />

This is the only solution I know but I suspect there is better one.

like image 650
Piotr Perak Avatar asked Sep 26 '22 04:09

Piotr Perak


People also ask

How do I pass multiple parameters on onChange?

To pass multiple parameters to onChange in React:Pass an arrow function to the onChange prop. The arrow function will get called with the event object. Call your handleChange function and pass it the event and the rest of the parameters.

How do you pass parameters to an event handler React?

Passing the event object of react as the second argument. If you want to pass a parameter to the click event handler you need to make use of the arrow function or bind the function. If you pass the argument directly the onClick function would be called automatically even before pressing the button.


2 Answers

I think this way is easier:

    <Input type="text"
                value={range.name}
                onChange={(e) => this.changeRangeName(range.id, e)}
        ...
    onChange(id, e) {
        ...
    }
like image 87
Egor Avatar answered Oct 20 '22 08:10

Egor


The event argument is still passed, but the rangeId argument is prepended to the arguments list, so your changeRangeName method would look like

changeRangeName: function (rangeId, event) {
    var newName = event.target.value;
},

See Function.prototype.bind()

like image 46
Alexandre Kirszenberg Avatar answered Oct 20 '22 07:10

Alexandre Kirszenberg