Search code examples
reactjsecmascript-6babeljsecmascript-2016

Avoid .bind in ES6(7?) with Babel


I have this in my JSX:

<Options options={options} onOptionSelect={this.onOptionSelect.bind(this)} />

However, I swear I've seen some fanciness to negate the need for .bind when passing callback methods down to child React components, am I right?


Solution

  • You can use an arrow function combined with property initialization.

    class Component extends React.Component {
      handleClick = () => {
        console.log(this.props);
      }
    
      render() {
        return <div onClick={this.handleClick} />
      }
    }
    

    Because the arrow function is declared in the scope of the constructor, and because arrow functions maintain this from their declaring scope, it all works. The downside here is that these wont be functions on the prototype, they will all be recreated with each component. However, this isn't much of a downside since bind results in the same thing.