12. JSX Events, Methods and Method Binding

We will learn how to apply JSX event handlers.

  
  class Watch extends React.Component {
    clickMe() {
      alert('clickMe');
    }
    render() {
      return (
        <div>
          <button onClick={this.clickMe}>Submit</button>
        </div>
      );
    }
  }

by using this button we are able to do events.

Method Binding: 

We will learn about 'this' binding on these event handlers.

This means that for render the 'this' binding is correct. But we have actually broken binding.

Try to access this.props.options instead of alert.

It will throw uncaught: TypeError cannot read property 'props' on null

When we try to read props of this, it is actually not available. because it is null.

'this' no longer refers to current class instance.

The problem of using your 'this binding' is not specific to ES6 classes.

"Uncaught Exception this undefined"

  
 const obj = {
    name: 'Praba',
    getName(){
      return this.name;
    }
  };

  const getName = obj.getName;
  console.log(getName());


We will check how to we set 'this' binding. 

lets integrate binding into our class as mentioned below.

This way we can bind the method.

 So we can bind in two ways

  1. Using constructor bind i.e calling bind method in constructor. 

  2. Inline bind

 
 class Options extends React.Component {
    constructor(props) {
      super(props);
      this.removeAll = this.removeAll.bind(this);
    }
    removeAll() {
      console.log(this.props.options);
      // alert('removeAll');
    }
    render() {
      return (
        <div>
          <button onClick={this.removeAll}>Remove All</button>
          {
            this.props.options.map((option) => <Option key={option} optionText={option} />)
          }
        </div>
      );
    }
  }

 Inline bind:

  <button onClick={this.removeAll.bind(this)}>Remove All</button>
  {
    this.props.options.map((option) => <Option key={option} optionText={option} />)
  }
  </div>

 

 

Comments