Chavdar Slavov
Chavdar Slavov

Reputation: 875

Multiple event handlers for the same event and element with Reactjs

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.

Upvotes: 3

Views: 3119

Answers (1)

Crob
Crob

Reputation: 15175

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

Upvotes: 5

Related Questions