3

I'm writing an extended version of the input element. Here is a simplified version of it:

var MyInput = React.createClass({
    render: function () {
        return (
            <div>
                <input type="text" onChange={this.changeHandler} {...this.props} />
            </div>
        );
    },

    changeHandler: function(event){
        console.log('Trigger me first');
    }
});

I'm using it in a context like this:

<MyInput placeholder="Test" value={this.state.myValue} onChange={function(event){
    console.log('Trigger me second');
}} />

As you are probably suspecting one onChange overrides the other depending on the order of the attributes.

With that in mind, what do you think would be the cleanest way to implement support for multiple event handlers for the same event, for the same element in cases like this one?

Edit


I was able to swap onChange and {...this.props} in the component and use
changeHandler: function(event)
{
        console.log('input_changeHandler change');
        this.props.onChange(event);
}

But I'm concerned if it's safe.

Chavdar Slavov
  • 865
  • 8
  • 22
  • I can't think of any reason that it wouldn't be safe. I've done similar things and it's worked out fine. – Crob May 05 '15 at 14:00
  • Does this answer your question? [Call multiple functions onClick ReactJS](https://stackoverflow.com/questions/26069238/call-multiple-functions-onclick-reactjs) – Krisztián Balla May 05 '20 at 12:50

1 Answers1

5

From the docs here https://facebook.github.io/react/docs/jsx-spread.html

The specification order is important. Later attributes override previous ones.

So if you put your onChange after the spread, it will always take precedence. You can then call the onChange function passed in from your own handler.

var MyInput = React.createClass({
    render: function () {
        return (
            <div>
                <input type="text" {...this.props} onChange={this.changeHandler} />
            </div>
        );
    },

    changeHandler: function(event){
        console.log('Trigger me first');
        if (typeof this.props.onChange === 'function') {
            this.props.onChange(event);
        }
    }
});
Crob
  • 14,807
  • 3
  • 31
  • 28