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().

0

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Generally prototype method that was bound with bind has more benefits than an arrow.
While arrow functions play a crucial part in this solution, you are actually using an experimental feature: 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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.