3.3: Arrow Functions
Last updated
Last updated
Arrow functions are incredibly common in React. It's important for you to know how they work.
Again, we recommend taking a through the documentation, if you haven't already. Some of the points below are cherry picked from there. Some points, like the 'this' keyword, we'll be discussing later.
Again, it is very common to see the Fat Arrow / Arrow Function syntax used with React, especially in Functional Components. The Fat Arrow provides a more terse and compact approach to writing a function, and React, while often verbose, strives to make things more compact. It's important to note that the Fat Arrow is part of ES6, plain old JS, which brings up a great point: You can (and will) often write plain JavaScript with React.
So here is the answer to writing the Component in arrow syntax:
If you don't understand what's going on, step away from your project for a second and have a look at this example. Just so you know, this is in vanilla JavaScript, not React specific:
Here's a regular JS function:
Here is that same function written with Arrow Syntax:
Notice in the above code, we don't have to use the 'return' keyword. It's implicitly added when there is a one line/expression in the body of the function.
Let's see another example, same thing straight from the MDN docs.
Consider the following example where the first and second version of the function are the same.
Here is a simple version that represents the syntax of our React Component.
Make sense? If it doesn't, we recommend more practice. You can't read React without knowing this concept.
Let's go on to the next module.