Cleaner React with Class Fields.

Now, write class methods that are automatically bound to the class instance without any overhead syntax.

This is possible because of this ECMAScript proposal.

And here’s the fiddle.


As you can see it eliminates the need for a this.doWork = this.doWork.bind(this) in the constructor and we can also avoid creating a new fat arrow function like so <button onClick={() => this.doWork()}> inside each render cycle.

What if the method takes an argument and is called with an item from an array?

No worries! Instead of doing work, just make the original return another arrow function and do the actual work inside the returned function.

The returned function will have access to the original argument via the power of closure.

And here’s the fiddle.

Cheers!

“Making the simple complicated is commonplace; making the complicated simple, awesomely simple, that’s creativity.”
Charles Mingus.