1

This is a very simple question but I am in the learning process and after reading around I could not find a good explanation to this, in the code below: What is the purpose of the line:

this.buttonClicked = this.buttonClicked.bind(this);

If I comment it, the program is still working. Most likely with some side effects but I don't know them yet...

class test extends React.Component {
constructor(props){
    super(props)
    //this.buttonClicked = this.buttonClicked.bind(this);
}

buttonClicked() {
    alert("thank you!")
}

render() {
    return (
        <div>
          <h2>{this.props.text}</h2>
          <button onClick={this.buttonClicked}>click me!</button>
        </div>
    )
}

}

3
  • It binds the execution scope of the callback to the current class. So referring to this in the callback will refer to your component instance Commented Oct 12, 2018 at 13:16
  • Most likely with some side effects but I dont know them yet - try alert(this.props.text) instead. Commented Oct 12, 2018 at 13:18
  • You could avoid using the binding and still access this by using arrow function Commented Oct 12, 2018 at 13:19

2 Answers 2

3

this.buttonClicked = this.buttonClicked.bind(this);

This line basically allows you to use this within your buttonClicked() function.

You don't notice a difference since you don't actually use this in that function.

Try something with this within buttonClicked() with the binding line commented out, and you should get an error.

To avoid needing to manually bind, you can use an arrow function, like:

buttonClicked = () => {
  // do something with `this`
}
Sign up to request clarification or add additional context in comments.

Comments

0

bind is used to bind the context. Explanation is already given in other answers.

you can use the following syntax instead of the commented line

onClick={this.buttonClicked.bind(this)}

1 Comment

Note: This creates a new function in every render.

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.