Multiple event handlers for the same event and element using Reactjs

I am writing an extended version of an input element. Here is a simplified version:

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 use it in context:

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

As you probably suspect, one onChange overrides the other depending on the order of the attributes.

Given this, do you think the cleanest way to implement support for multiple event handlers for the same event for the same element in such cases?

Edit


I managed to exchange onChange and {...this.props} for the component and use
 changeHandler: function(event) { console.log('input_changeHandler change'); this.props.onChange(event); } 

But I worry if it is safe.

+3
javascript reactjs
source share
1 answer

From the documentation here https://facebook.imtqy.com/react/docs/jsx-spread.html

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

So, if you put your onChange after distribution, it will always take precedence. Then you can call the onChange function passed 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); } } }); 
+4
source share

All Articles