Arrow function as class function in ES6

If you’ve been using create-react-app and tried to build things on your own you might have done/seen/used

handleClick = () => {
// do thing on click
}

This comes from the Class properties transform plugin from Babel: https://babeljs.io/docs/plugins/transform-class-properties/

So if you try to build a project on your own you’ll need to include it to use that syntax so babel knows what to do with it. Otherwise you can do:

onClick={(e) => this.handleClick(e)

In the jsx itself but it *can* have performance issues if you are passing that onClick down as a prop.

I’ve not gone deep enough down the big app building track with a bunch of things composited in a way where this was an issue so I’ve used both. With that said…after thinking about this and going through it manually over the weekend I’ll probably get in the habit of using the public class fields syntax unless I see it get a notice that it has been deprecated for some reason in babel or I stop using babel to transpile.

View All

Leave a Reply

Your email address will not be published. Required fields are marked *