Multiple event handlers for the same event and element with Reactjs

All we need is an easy explanation of the problem, so here it is.

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.

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

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

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply