Codementor Events

A Beginner’s Guide to React with ES6

Published May 15, 2019


Cover Image by Edmond Atto

What is React?

React is a JavaScript library for building user interfaces, that is maintained by Facebook as an Open Source project under the MIT license. Over the past year or so, it has gained widespread popularity in the developer community as well as a large community of contributors. At the time of publishing this book, React was the 3rd most starred library and/or Framework on Github (behind Bootstrap and TensorFlow)with 93.9k stars. It is safe to say then, that you deciding to learn React is a great decision.

It has to be emphasised that React is NOT a framework; it is a library! This is a common misconception many developers have as they start out on their React journey. As a library, React depends on other libraries such as React Router, Redux, Prop-types etc. to extend its already extensive capabilities.

React deals entirely with the look (user interface) of your web application, that is to say, it is purely presentational. React Native which is beyond the scope of this book, helps you to design user interfaces for android and iOS apps. Refer to the official documentation for more information on React Native.


Is React really for me?

If you’re interested in building modular interfaces for web applications, then the short answer is yes, React really is for you.

Because React is a JavaScript library, you will get the most out of this book if you know the basics of JavaScript, specifically the modern features of ECMAScript 6 (ES6 or JavaScript 2015) that we’ll be using over the course of the book.

Do not worry if you do not know much about JavaScript. Towards the end of this introductory chapter, there is an overview of the JavaScript concepts that will be used in this book.

You are also encouraged to brush up on the basics of JavaScript from here and continue with this book when you’re all caught up.

Why React?

React offers up a variety of benefits that have driven its rise in popularity. Let us review a couple of them real quick:

=> Getting started is easy
React is basically JavaScript, so, as long as you know its basics, you’re good to go! The React API is quite simple to use and you will be able to create your first component with very limited markup.

=> Easy DOM (Document Object Model) manipulation
In the past, using the actual DOM API was a pain, a fact that made it difficult for developers to manipulate the DOM. React solves this problem by providing a virtual DOM (in memory) that acts as an agent between the developer and the real DOM. The virtual DOM is a lot more user friendly for developers.

=> Speed
Because of React’s virtual DOM, it has a pretty cool way of handling changes to a web page; React is constantly listening for changes to the virtual DOM. It keeps a record of the actual DOM tree and when a change is detected on the virtual DOM, React calculates the differences between the two, it reacts to this change by making the changes and re-rendering only the elements on the DOM that have changed. This precision is what makes React lightning quick.

=> React is declarative
React allows you to describe what the application interface should look like as opposed to you describing how it should build the UI. React makes it such that you are not concerned with the details of how the different UI elements are created and rendered, giving you more time to think about what look you want to achieve with your interfaces as opposed to the tiny details of how to make that happen. Declarative programming is becoming more advanced and bringing more and more exciting features to the space. This post by Tyler Mcginnis is a good place to start finding more information on declarative programming vs imperative programming.

=> React makes use of reusable components  
A component is simply a function/class that returns a section of your interface. Building an application with React allows you to reuse components in different sections of your application. It follows the pattern of creating a component once and declaring it in multiple locations as required. This helps you write a lot more maintainable code as it’s easy to make cascading changes throughout your application.

=> Unidirectional data flow  
React applications are built as a combination of parent and child components. As the names suggest, each child component has a parent and a parent component will typically have one or more child components. Components receive data via props and in the case of a parent and child component, props are passed down from the parent to the child. Data (props) is never passed up from the child to the parent, hence the phrase, unidirectional data flow. This is a powerful concept because it leads to a more predictable application and creates a single source of truth so that any changes to the parent’s state propagate to all its children consistently.

=> Powerful type-checking using PropTypes
With the power of PropTypes, React allows you to protect your components from abuse (and catch bugs early) by strictly and efficiently enforcing type-checking on the props(props are to components what arguments are to functions) passed to them without the need to add the complexity that comes with using TypeScript or flow for type-checking in your project.

As of React 15.5.0, PropTypes is no longer part of the React core package but is used as a separate dependency.

=> Large community
React’s popularity ensures an ever growing community around it, which means, there’s a ton of resources out there to help you as you grow your skills. More importantly, packages such as React-router and React-redux that extend React’s capabilities are actively maintained.

As you start out, these concepts may seem numerous and confusing; do not lose steam if everything doesn’t make sense right now. During the course of reading the book, things will get a lot clearer. Reviewing earlier sections of the book as you go along will help you to further internalise the content.


Setting up your first React Application

There are numerous ways and tools out there to help you setup a React app, however, throughout this book, the official create-react-app CLI tool created by the Facebook team will be used.

According to the official React documentation, create-react-app is the best way to start building a new React single page application. It sets up your development environment so that you can use the latest JavaScript features, provides a nice developer experience, and optimizes your app for production, all without requiring any configuration on your part.

Before the create-react-app CLI tool was created by the Facebook team, developers had to deal with setting up the applications with the right set of dependencies such as babel, react-dom as well as code linters. Additionally, they would have to create a custom webpack configuration file for every React app they worked on. With the CLI tool, developers can instantly jump into active development with minimal bootstrapping.

Before you can get started enjoying the create-react-app goodness, you’ll need to make sure you have Node >= 6 installed on your machine. If you do not have Node installed on your machine, no worries, this guide will have you set up in no time.

Create-react-app is available for Windows, Linux and MacOS so, you should be covered. Still not sure if you should use create-react-app? Reading this should help.

Enough talk, let’s get you started and walk you through the simple process of creating a React app with create-react-app.

> Install create-react-app globally

npm install -g create-react-app

> Run create-react-app by passing it the desired name of your app

create-react-app my-new-app

> cd into your new app’s directory and start your brand new app

cd my-new-app
npm start

> Navigate to localhost:3000 in your browser


A screenshot of your new application at localhost:3000

Congratulations! You just created your first React application. You’re well on your way to building bigger and better things.


Commonly used ES6 Features

Throughout the rest of this book, a number of ES6 features will be used consistently. If you do not have prior experience with ES6 features, this brief introduction will come in handy. If you’re comfortable with ES6 features, skip this section and head to chapter 2 to get started writing your first component.

let and const

let and const are two new keywords that were introduced in ES6 for declaring variables. When used to declare variables, they are scoped to the block and not the function; this means they are only available within that block. Variables declared with let can be re-assigned but cannot be redeclared within the same scope whereas those declared by const must be assigned an initial value but cannot be redeclared within the same scope.

In summary, use let when you plan on re-assigning new values to the variable and const if you’re not planning to re-assign a variable. See an example of using let

let name = 'Edmond';
name = 'Atto';
console.log(name);

//output
Atto

The spread operator

The spread operator denoted by … is used to expand iterable objects into multiple elements as shown in the example below.

const cities = ["Kampala", "Nairobi", "Lagos"];
console.log(...cities);

//output
Kampala Nairobi Lagos

The spread operator can also be used to combine multiple arrays into one array containing all array elements as shown below.

const east = ["Uganda", "Kenya", "Tanzania"];
const west = ["Nigeria", "Cameroon", "Ghana"];

const countries = [...east, ...west];
console.log(countries);

//output
['Uganda', 'Kenya', 'Tanzania', 'Nigeria', 'Cameroon', 'Ghana']

Template literals

Before ES6, strings were concatenated using the + operator as shown in the example below.

const student = {
 name: 'John Kagga',
 city: 'Kampala'
};

let message = 'Hello ' + student.name + ' from ' + student.city;
console.log(message);

//output
Hello John Kagga from Kampala

ES6 introduced template literals which are essentially string literals that include embedded expressions. They are denoted by backticks instead of single or double quotes. The template literals can contain placeholders which are represented by ${expression}. The quotes and + operator are dropped when using template literals as shown in the rewrite of the above example below.

let message = `Hello ${student.name} from ${student.city}`;

//output
Hello John Kagga from Kampala

Default function parameters

ES6 introduced a way of adding default values to the function’s parameter list as shown below.

function greet(name = 'Fellow', greeting = 'Welcome') {
 return `${greeting} ${name}`;
}

console.log(greet()); // Welcome Fellow
console.log(greet('Kagga')); // Welcome Kagga
console.log(greet('Mike', 'Hi')); // Hi Mike

A default parameter is created when an equal ( = ) is added and whatever the parameter should default to if an argument is not provided (this parameter) can be any JavaScript data type.

Destructuring

In ES6, data can be extracted from arrays and objects into distinct variables using destructuring. Here are a couple of examples

  1. Extracting data from an array

=> Before ES6

const points = [20, 30, 40];

const x = points[0];
const y = points[1];
const z = points[2];

console.log(x, y, z);

//output
20 30 40

=> With ES6

The above example can be changed to use destructuring in ES6 as shown below.

const points = [20, 30, 40];

const [x, y, z] = points;

console.log(x, y, z);

//output
20 30 40

The [] represent the array being destructured and x, y, z represent the variables where the values from the array are to be stored. You do not have to specify the array indexes because they are automatically implied. During destructing some values can be ignored for example the y value can be ignored as shown below.

const [x, , z] = points

2. Extracting data from an object

=> Before ES6

const car = {
 type: 'Toyota',
 color: 'Silver',
 model: 2007
};

const type = car.type;
const color = car.color;
const model = car.model;

console.log(type, color, model);

//output
Toyota Silver 2007

=> With ES6

const car = {
 type: 'Toyota',
 color: 'Silver',
 model: 2007
};

const {type, color, model} = car;

console.log(type, color, model);

//output
Toyota Silver 2007

The { } represent the object to be destructed and type, color, model represent the variables where to store the properties from the object. There is no need of specifying the property from where to extract the value from because car already contains a property called type and the value is automatically stored in the type variable.

As with array destructuring, object destructing enables extraction of only the values needed at a given time. The example below shows the extraction of only the color property from the car object.

const {color} = car;
console.log(color);

//output
Silver

Object literal Shorthand

ES6 provides a new way of initialising objects without code repetition, making them concise and easy to read. Prior to ES6, objects were initialised using the same property names as the variable names assigned to them as shown below:

let type = 'Toyota';
let color = 'Silver';
let model = 2007;

const car = {
 type: type,
 color: color,
 model: model
};

console.log(car);
//output
{ type: 'Toyota', color: 'Silver', model: 2007 }

Looking closely at the above example, it is clear that type:type, color:color and model:model seem redundant. The good news is that you can remove those duplicate variable names from object properties if the properties have the same name as the variables being assigned to them as shown below.

let type = 'Toyota';
let color = 'Silver';
let model = 2007;

const car = {
 type,
 color,
 model
};
console.log(car);

//output
{ type: 'Toyota', color: 'Silver', model: 2007 }

Arrow functions

ES6 introduced a new kind of functions called arrow functions which are very similar to regular functions in behaviour but different syntactically.

As an example, follow the steps below to convert the given regular function into an arrow function.

function (name) { 
  return name.toUpperCase();
}
  • remove the function keyword
  • remove the parentheses
  • remove the opening and closing curly braces
  • remove the return keyword
  • remove the semicolon
  • add an arrow ( => ) between the parameter list and the function body

The result

name => name.toUpperCase();

Using arrow functions
As opposed to regular expressions which can either be function declarations or function expressions, arrow functions are always expressions which can only be used where expressions are valid. Arrow functions can be stored in a variable, passed as an argument to a function or stored in an object’s property.

Parentheses and arrow function parameters
If an arrow function parameter list has one element, there is no need of wrapping that element in parentheses.

name => `Hello ${name}!`

But, if there are two or more items in the parameter list or zero items, the list has to be wrapped in parentheses as shown below.

const hello = () => console.log('Hello React!'); //zero parameters
hello();

const location = (name, city) => console.log(`${name} is from ${city}.`);//two parameters

location('John', 'kampala');

Block body syntax
When there is need to have more than one line of code in the arrow function body, the block body syntax has to be used. With the block body syntax, curly braces have to be used to wrap the function body and a return statement has to be used to actually return something from the function has shown below.

name => {
  name = name.toUpperCase();
  return `${name.length} characters make up ${name}'s name`;
};

Benefits of using arrow functions
Arrow functions may be preferred because of the following:-

=> short syntax
=> they are easy to write and read 
=> they automatically return when their body is a single line of code.

Classes

ES6 introduced classes that are simply mirage that hides the fact that prototypal inheritance goes on under the hood. These classes are unlike those in class based languages like Java. Below is an example of an ES6 class.

class Animal {
 constructor(numLegs) {
   this.numLegs = numLegs;
   this.mammal = false;
 }

 isMammal() {
   this.mammal = true;
 }
}

When a new object is constructed from the Animal class , the constructor will run and the variables inside it will be initialised.

Benefits of using classes
With the new class syntax, less code is required to create a function. The function contains a clearly specified constructor function and all the code needed for the class is contained in its declaration.

ES6 also introduced two new keywords, super and extends which are used to extend classes.

Note that classes in javascript are still functions and their behavior is not the same as those in object oriented programming languages such as Java.

This was a brief, high-level introduction to the ES6 features that will be used throughout the book. It is not meant as a replacement for any fully fledged ES6 resources out there. Refer to this resource to learn more about ES6 features.

Take a moment to relax, maybe take a break. You now know a lot about React and ES6. When you are ready, head over to chapter 2 and write your first component! See you there!


If you’d like to skip ahead to the other chapters, find links to them below:

Understanding React Components
_Chapter 2 from the book; Vumbula React — Co-authored by Edmond Atto_medium.com

Understanding the Fundamentals of State in React
_Chapter 3 from the book; Vumbula React — Co-authored by John Kagga_medium.com

Handling User Input in React — CRUD
_Chapter 4 from the book; Vumbula React — Co-authored by Edmond Atto_medium.com

If you found this article the least bit helpful, hit the 👏 button and help me get it to more people who need help getting started with React. I’d appreciate your responses with your thoughts as well — whatever they might be. I’m on Twitter if you need to chat.

Discover and read more posts from Edmond B. Atto
get started
post commentsBe the first to share your opinion
Show more replies