freeCodeCamp Challenge Guide: Bind 'this' to a Class Method

Bind ‘this’ to a Class Method


Problem Explanation

If a method on a JavaScript class needs to access some internal state of the instance, like this.state, the method needs to be bound to the instance of the class.


Hints

Hint 1

Like many things in programming, there is more than one way to bind this. For this challenge, we are going to stick with constructor binding.

class MyClass {
  constructor() {
    this.myMethod = this.myMethod.bind(this);
  }

  myMethod() {
    // whatever myMethod does
  }
}

Solutions

Solution 1 (Click to Show/Hide)
class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      text: "Hello"
    };
    this.handleClick = this.handleClick.bind(this);
  }
  handleClick() {
    this.setState({
      text: "You clicked!"
    });
  }
  render() {
    return (
      <div>
        <button onClick = {this.handleClick}>Click Me</button>
        <h1>{this.state.text}</h1>
      </div>
    );
  }
};

Relevant Links

21 Likes