Binding `this` in React

This is for explaining the usage of .bind(this)in React components.


Firstly I will create a React component with JS ES6 class.

class Greeting extends React.Component {
  constructor(props){
    super(props);
    this.state = {
      text: ""
    }
    //the binding section
    this.clicked = this.clicked.bind(this);
  }
  clicked(){
    this.setState=({
      text: "Hello!"
    });
    render() {
      <button onClick={this.clicked}>Click</button>
      <h1>{this.state.text}</h1>
    }
  }
}
ReactDOM.render(<Greeting />, document.querySelector("body"));

As you can see, I assigned this.clicked to this.clicked.bind(this).
At there the this keyword in the bind method mean the whole component.
And the .bind() method give access the whole component’s data to the this.clicked function.
So that when the this.setState is called in the this.clicked the this mean the component, not the this.clicked function.
Therefore you can change the data of the component state.


For more:

1 Like

So is this meant for the Hint page?

The page already has the solution and it links to a news article that goes more in-depth on the subject. I did update the post with a link to MDN on Function.prototype.bind() and cleaned it up a bit. But I don’t really think we need to expand on the subject.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.