0
  export default class DetailsPage extends React.PureComponent {
constructor() {
    super();
     this.state = {
        data: '',
        isModalOpen: false,
    };

  **//this.openModal = this.openModal.bind(this);**
    }
openModal() {
      console.log(this, "this in Handler");
    this.setState({ isModalOpen: true });
}

closeModal() {
    this.setState({ isModalOpen: false });
}

Case 1 (No Binding in click Handler )

    render() {

    return (

       (<div className="left">

                <button className="btn btn btn-primary" type="button" 
                 onClick={this.openModal}>Edit</button>
         </div>
       );
     )
  }
}

Case 2 (Binding with this)

    render() {

    return (

       (<div className="left">

                <button className="btn btn btn-primary" type="button" 
                 onClick={this.openModal.bind(this)}>Edit</button>
         </div>
       );
     )
  }
}

In my click Handler openModal() I have written console.log(this)

In Case 1 : the value of "THIS" comes out to be NULL in react .

In Case 2 : the value of "THIS" comes out to be that of component (that is perfectly okay).

My doubts:

  1. why does "THIS "comes out to be NULL in the first case.

  2. What is the use of super() in constructor ? I have read about it and got to know what happens if we remove the super() and difference between super() & super(props). But I want to know the functionality that happens in the background when we call super().

rajat44
  • 4,941
  • 6
  • 29
  • 37

1 Answers1

0

This question has been asked and answered in a variety of ways -- but my favorite is probably the ES2015 arrow function syntax:

class Foo extends React.Component {
    someMethod = () => {
        // "this" is bound automatically!
        console.log(this, "this in Handler");
        this.setState({ isModalOpen: true });
    }
}

As a caveat, there are pros and cons to always doing this -- the most often-quoted being "performance". Twitter wars have been fought over this, but IMO Ryan Florence (co-author of React Router) said it best.

arthurakay
  • 5,631
  • 8
  • 37
  • 62
  • Generally prototype method that was bound with `bind` has [more benefits](https://stackoverflow.com/a/43601993/3731501) than an arrow. – Estus Flask Sep 19 '17 at 13:57
  • While arrow functions play a crucial part in this solution, you are actually using an experimental feature: https://github.com/tc39/proposal-class-fields . Also, the performance debate you mention is about *inline* event handlers, i.e. functions defined in the render method. Yours is create different at construction time. – Felix Kling Sep 19 '17 at 14:25