Binding Events Programmatically (SyntheticEvent)
I have a container with several blocks input
(with different properties). I would like to change the keydown behavior for all of them. I am wondering if there is a better way than to manually place the property onKeyDown={this.handleKeydown}
on each <input>
.
Since ReactJS has its own system SyntheticEvent
, I don't want to bind regular javascript events that might interfere with the ReactJS event system.
Is this possible with React?
source to share
Two options come to mind
-
You can use jsx spread object and attributes
var props = {onKeyDown: this.handleKeyDown}; return ( <input {...props} name="foo" /> <input {...props} name="bar" /> <input {...props} name="qux" /> );
-
You can create a custom component
var MyInput = React.createClass({ handleKeyDown: function() { // ... }, render: function() { return ( <input onKeyDown={this.handleKeyDown} /> ); } });
Then use it like in another component
render: function() { return ( <MyInput name="foo" /> <MyInput name="bar" /> <MyInput name="qux" /> ); }
source to share