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.

2
  • I can't think of any reason that it wouldn't be safe. I've done similar things and it's worked out fine. Commented May 5, 2015 at 14:00
  • Does this answer your question? Call multiple functions onClick ReactJS Commented May 5, 2020 at 12:50

1 Answer 1

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);
        }
    }
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.