Skip to content

Instantly share code, notes, and snippets.

@vasanthk
Last active September 15, 2015 18:15
Show Gist options
  • Save vasanthk/15a8b19bbbdad762be7d to your computer and use it in GitHub Desktop.
Save vasanthk/15a8b19bbbdad762be7d to your computer and use it in GitHub Desktop.
AutoBinding in React

AutoBinding in React

Just for quicker reference from here

1. ES5 (No class)

var Button = React.createClass({
  handler:function(e){
   ....
  },
  render:function(){
    return (
      <button onClick={this.handler} >
        Click me
      </button>
    );
  }
})

2. Using bind syntax

class Button extends React.Component{
    handler(){
     ...
    }
    render(){
       return (
          <button onClick={this.handler.bind(this)} >
            Click me
          </button>
       );
    }

}

3. Binding in constructor

class Button extends React.Component{
    constructor(){
    this.handler = this.handler.bind(this) 
    }
    handler(){
     ...
    }
    render(){
       return (
          <button onClick={this.handler} >
            Click me
          </button>
       );
    }

}

4. Fat arrows

class Button extends React.Component{
    handler = ()=>{
     ...
    }
    render(){
       return (
          <button onClick={this.handler} >
            Click me
          </button>
       );
    }

}

5. ES7 Bind syntax in constructor

class Button extends React.Component{
    constructor(){
    this.handler = ::this.handler;
    }
    handler(){
     ...
    }
    render(){
       return (
          <button onClick={this.handler} >
            Click me
          </button>
       );
    }

}

6. ES7 Bind syntax inline

class Button extends React.Component{
    handler(){
     ...
    }
    render(){
       return (
          <button onClick={::this.handler} >
            Click me
          </button>
       );
    }

}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment