Use ES2016 Property Initializer Syntax in ES6 classes

Andy Van Slaars
InstructorAndy Van Slaars
Share this video with your friends

Social Share Links

Send Tweet

Create react app provides support for es2016 property initializer syntax out of the box. In this lesson, we’ll refactor the App component to use property initializers and look at the advantages of this syntax.

[00:00] In this component, we're using the constructor to define this application's initial state. We're also binding the custom methods that we've defined to this, ensuring that those methods have the correct context when reading state and calling set state for updates.

[00:14] These binding statements are a bit redundant. They are also easy to forget about, so you try to run your app, and a call to set state doesn't work as expected. Luckily, create React app shifts with the proper configuration to allow us to use property initializer syntax.

[00:29] To demonstrate, let's convert the code in this constructor into property initializers. I'm going to start by grabbing the entire initial state object, and cutting that, and putting it above the constructor. I'm going to remove the reference to this.

[00:44] With property initializer syntax, state is now an instance property of this class just like it was before, and it's still available as this.state in this component's methods. Let's take a look at these method bindings. Each one of these is simply binding this to the method so that we have access to this.setState and this.state within those methods.

[01:08] If we initialize these methods as properties, then we don't need to add this extra binding. For this, all we have to do is update each of these. We're going to set handle submit as a property, to equal an error function that handles our event. I'm going to do the same thing with handle empty submit.

[01:26] Adding equal sign and a fat arrow. The same again with handle input change. Now that we've made those updates, we can come back up to our constructor and we can get rid of these extra bind statements. Now that we've done all that refactoring, we're left with a constructor that simply calls super.

[01:46] If I save this, and without the browser reload, we can come over here and I'm going to open up the dev tools. We'll see in the console that there's a warning that we have a useless constructor. We can just go in here and we can take the constructor out, because we're no longer doing anything unique to our component limit.

[02:04] We can save that again. When the browser reloads the useless constructor warning goes away. We can verify that we didn't break anything with our refactoring. We'll try to submit an empty form. We'll get a warning.

[02:22] If I give it a valid entry, I should be able to submit. It updates our to-do list.