Find your content:

Search form

You are here

why we need to bind event handlers in Class Components in React? React Interview Questions, HelpInterview

 
Share

Built in methods and attributes accessible using this context in JSX. Whatever the new methods created it needs to be binded before use it in the JSX.

If methods are not binded with component then using from html or JSX it lose the context and it produce undefined.

class Foo extends React.Component{
  constructor( props ){
    super( props );
  }
  
  handleClick(event){
    // your event handling logic
  }
  
  render(){
    return (
      <button type="button" 
      onClick={this.handleClick}>
      Click Me
      </button>
    );
  }
}

ReactDOM.render(
  <Foo />,
  document.getElementById("app")
);

above code returns undefined on the onClick because handleClick is not binded with class Foo.
class Foo extends React.Component{
  constructor( props ){
    super( props );
    this.handleClick = this.handleClick.bind(this);
  }
  
  handleClick(event){
    // your event handling logic
  }
  
  render(){
    return (
      <button type="button" 
      onClick={this.handleClick}>
      Click Me
      </button>
    );
  }
}

ReactDOM.render(
  <Foo />,
  document.getElementById("app")
);

My Block Status

My Block Content