Faiz Halde Faiz Halde - 6 days ago 5
Javascript Question

this object in React Component using ES6 classes

I have a

MsgInput
component with a
textarea
which
onKeyUp
triggers a handler function. Inside the handler function, I try reading the props using
this.props
, but not sure why props is undefined here. Ofcourse the workaroud is to use
this.handler.bind(this)
.

export class MsgInput extends React.Component {
constructor(props) {
super(props);
}

inputHandler(e) {
if(e.keyCode == 13 && !e.shiftKey) {
this.props.onNewMessage({content: e.target.value});
e.target.value = '';
e.preventDefault();
}
}

render() {
return (
<div className="controls">
<textarea onKeyDown={this.inputHandler.bind(this)} className="msg-input" placeholder="Write something" disabled={!this.props.auth}></textarea>
</div>
);
}
}

leo leo
Answer

React with ES6 classes doesn't auto bind your callbacks to the component instance, so you have to do it yourself as you already did. Otherwise this would not available in the callback.


this.inputHandler.bind(this)

This is not a work around, but the way it is supposed to be.

Another alternative is to utilise ES6 arrow functions which would automatically bind this.

<textarea onKeyDown={(e) => this.inputHandler(e)}></textarea>