ES6 Arrow functions in React

Linked Projects:


‚ú® 1 person thanked Hrishi Mittal for this tutorial.

ūüĎć Send Thanks

Lesson links:

Lesson code -

Now we’re going to look at another ES6 feature - arrow functions.

Arrow functions are shorthand functions which automatically bind to the surrounding context.

So we don’t need to explicitly write .bind(this). Let’s try it in the AppointmentForm component.

We can change this.handleSubmit and this.handleChange like this:
Arrow functions

Now let's try the app in the browser. I am able to type in the title input field but we’re getting some warnings.
Warning: Cannot read property target of undefined.
Oh yes we need to pass in an event to the handleChange and handleSubmit functions.

And let’s also add an arrow function to the Datetime input.

Pass event to handler functions
If we try the app again in the browser, it works and we're able to create an appointment.

Now let’s add arrow functions in the Appointments component for onUserInput and onFormSubmit.
Add arrow functions in the Appointments component
Let's also change the variables in this component to constants by replacing the var keyword with const.

One final place we can add another arrow function is in the handleFormSubmit function inside the .done call.
Replace the explicit bind with an arrow function
So that's a quick introduction to arrow functions.

Liked this tutorial? Get more like this in your inbox