ffff
ffff

Reputation: 3070

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

Upvotes: 1

Views: 222

Answers (1)

Lyubomir
Lyubomir

Reputation: 20027

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

Upvotes: 3

Related Questions