In React class components we have to bind event handlers. I was so curious to know the reason behind. From google I found that , in the React Component , the this value will be undefined since the context was lost after passing the handler as a callback.

import React, { Component } from 'react';

class App extends Component {
  constructor() {
    super();
    this.state = {
      value: 0      
    }
    this.onClick = this.onClick.bind(this);
  }  

  onClick(){
    this.setState(function(prev,prop){
        return {
          value:prev.value+1        
        }
    });
  }


  render(){
    return( 
      <div>
        <div>render->state={this.state.value}</div>
        <button onClick={this.onClick}>Click-setState</button>       
      </div>
    );
  }
}

export default App;

In the above code ,

  1. How event handler method (this.onClick) is passed as a call back?.

  2. How context is being lost when this event handler passed as a call back?.

0 Answers