3.3: Arrow Functions

Arrow functions are incredibly common in React. It's important for you to know how they work.

Again, we recommend taking a read 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.

Arrow Syntax Answer

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:

import React from 'react';

const FunctionalComponentDemo = () => {
    return (
        <div className="main">
            <div className="mainDiv">
                <div>
                    Hello React
                </div>
                <div>
                    How are you today?
                </div>
            </div>
        </div>
    );
};

export default FunctionalComponentDemo;

Answer discussion

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:

var add = function(x, y){
    return x + y;
}

Here is that same function written with Arrow Syntax:

var add = (x, y) => x + y;

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.

// concise body syntax, implied "return"
var func = x => x * x;                  

// with block body, explicit "return" needed
var func = (x, y) => { return x + y; };

Consider the following example where the first and second version of the function are the same.

let greetUser = username => `Hello, ${username}!`;
let greetUserSecondVersion = username => { return `Hello ${username}!` };
console.log(greetUser('Kenn') === greetUserSecondVersion('Kenn')); // true

Here is a simple version that represents the syntax of our React Component.

var function = () => {
    console.log("Hello React");
}

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.

Last updated