Cleaner React with Class Fields.

Mustansir Zia
Sep 4, 2018 · 1 min read

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

This is possible because of this ECMAScript proposal.

Image for post
Image for post

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.

Image for post
Image for post

And here’s the fiddle.

Cheers!

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

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store