mohammad chughtai
mohammad chughtai

Reputation: 1964

What does this.function = this.function.bind(this) do in the following context? ReactJS

I am following a tutorial series on udemy and the instructor hasn't really explained the following line of code:

this.getrandomnum = this.getrandomnum.bind(this);

So I am a bit confused as to what it does and was hoping to get some help. My code works with or without the above line.

Here is the full code:

class App extends Component {
  render() {
    return (
      <div className="App">
      <h1> Hello</h1>
      <Body />
      </div>
    );
  }
}

class Body extends Component{
  constructor(props){
    super(props);
    this.state = {};
    this.getRandomNumber = this.getRandomNumber.bind(this);
  }
  getRandomNumber(){
    console.log('some random number')
  }
  render(){
    return (
      <button onClick={this.getRandomNumber}>Random Number</button>
      )
  }
}

Upvotes: 2

Views: 1413

Answers (1)

KA01
KA01

Reputation: 4251

It binds this to the function in the class when it's called. It's importance is to retain the context of this when it's called. Typically this is done on callbacks such as the onClick handler in the Body component.

Your code still works because you're not referencing any type of context (other than the window.console function, which is the this in this case). If you didn't bind this in the constructor and had this:

<button onClick={this.getRandomNumber}>Random Number</button>

and in the getRandomNumber:

getRandomNumber(e){
    console.log(e)
}

it would return an error that e is undefined because the context of this function is bound to the window object. In this case e does not exist.

Read more about: handling events in the React docs and bind

Upvotes: 1

Related Questions