Alejandro
Alejandro

Reputation: 83

React-JavaScript purpose of a line in the code

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

}

Upvotes: 1

Views: 112

Answers (2)

Colin Ricardo
Colin Ricardo

Reputation: 17239

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`
}

Upvotes: 3

Viswanath Lekshmanan
Viswanath Lekshmanan

Reputation: 10083

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

Upvotes: 0

Related Questions