If you have been using react components, you might have been accustomed to use ‘this’ binding inside the constructor with little awkward syntax as shown below.
class Person extends React.Component { constructor(props) { super(props); this.foo = "Dude it's nothing but foo"; //additional event binding for 'this' this.handleClick = this.handleClick.bind(this); } handleClick() { //do event handling here .. console.log(this.foo); } render() { return ( < button onClick = { this.handleClick } > Click Me < /button> ); } }
Inside the constructor you have to use following line of code for ‘this binding’.
//additional event binding for 'this' this.handleClick = this.handleClick.bind(this);
To avoid this kind of syntax you can use ES6 stage 2 presets from babel or individual transform class properties plugin.
These type of modern JavaScript syntax is being evolved from TC 39 group. Browser support is not that acceptable to use them directly but since we are using babel we do not want to worry about it since they will be transformed to ES5.
You can use following steps to use class transform babel plugin.
First go to your project root and enter following command in command prompt.
yarn add babel-plugin-transform-class-properties@6.24.1
Inside your babel rc file add following to your plugins array.
{ "plugins": ["transform-class-properties"] }
After these steps babel will use the plugin to transform your classes along the babel pipeline.
This allows you to use following more simplified syntax.
If you have been using react components, you might have been accustomed to use ‘this’ binding inside the constructor with little awkward syntax as shown below.
class Person extends React.Component { foo = "Dude it's nothing but foo"; constructor(props) { super(props); } handleClick = () => { //this binding works here console.log(this.foo); } render() { return ( < button onClick = { this.handleClick } > Click Me < /button> ); } }
With the stage 2 class properties you do not need to write rebinding this syntax in constructor.
…..happy coding….