1

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

1 Answer 1

3

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>

Caveat: Using .bind or arrow function inside your jsx will create a new function on every render which is a performance impediment.

As a last resort you can bind methods in your constructor which wouldn't have the performance penalty of arrow functions.

constructor(props) {
    super(props);
    this.inputHandler = this.inputHandler.bind(this);
}
Sign up to request clarification or add additional context in comments.

4 Comments

plus one for arrow functions. the calling of bind seemed tedious to me
nice, thanks;-) you can accept the answer if it clears things up.
Why create a new function on every render? I'd rather .bind inside the constructor.
yeah, that's another point. Functional callback is created every time on redner.

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.