React Tutorial

You are currently reading React Tutorial: The Complete Beginner's Guide to the React JavaScript Library — a free, online book that is designed to get developers up-and-running with React as quickly and as easily as possible.

Getting Started

This is chapter 2 of 14. Go to next chapter »

In this book, we’re going to build Leaderboard, an application that allows users to create and manage a list of players, with each player having a score that can either be increased or decreased with the click of a button.

Here’s what the application looks like:

Obviously, it’s not the most attractive application in the world, but that’s sort of the point. This isn’t a book about interface design, after all. This is a book about React, and it’s incredible how many features of React we can explore without losing ourselves in an overly complex example project.

To play with the application yourself, visit the following link:

leaderboard-react-demo.netlify.com

It doesn’t have many features, but take a few minutes to ensure that you’ve clicked every button and otherwise explored the final product that we’ll be building throughout the coming chapters.

Here are the most notable features:

  • There’s a list of players.
  • Each player has a “name” and a “score”.
  • Players are ranked by their score (from highest to lowest).
  • You can click a player to select them.
  • You can add players to the list.
  • You can remove players from the list.
  • When removing a player, you’ll be asked for confirmation.
  • You can “Give 5 Points” to a player.
  • You can “Take 5 Points” from a player.

The most difficult thing about learning something technical is often having a clear idea of what you’re trying to accomplish, so knowing where we plan to end up is only going to make learning React a more straight-forward process.

It’s worth noting that, since React is only used for building interfaces, this application doesn’t have any kind of back-end. There’s no database, basically, so if you refresh the page, any changes you’ve made to the data will be reset. This was a conscious choice, as connecting the interface to a back-end would only narrow the focus of this book, whereas I wanted to ensure that every chapter was something that every beginning React developer could use without sending them down an overly specific path. Fortunately, by the end of this book, the “connecting the interface to a back-end” part won’t be too difficult to figure out yourself (with a little help from Google, of course).

Installing React, Part 1

There’s a handful of a ways to install the React library, each with their own advantages and disadvantages. We’re going to use the option that combines ease of use with flexibility, but to better understand the React ecosystem, it’s worth taking a moment to explore all of the most common options.

Option #1: Embedding JavaScript

Because React is a JavaScript library, the simplest way to “install” it is to simply include it between the head tags of any standard HTML page.

To do this, use the following tags to embed the files from a CDN (rather than having to download the files yourself and store them locally):

<script src="https://unpkg.com/react@15/dist/react.js"></script>
<script src="https://unpkg.com/react-dom@15/dist/react-dom.js"></script>

This code is used for embedding two files:

  • react.js
  • react-dom.js

The reason the library is split across two files is because, as we talked about earlier, React can be used to develop interfaces on a range of platforms, such as the web and mobile devices. As a result, the “react.js” file contains the parts of React that are used across every platform, whereas the “react-dom.js” file contains the parts of React that are specific to developing for the web. If you were developing native mobile applications, you would not include the code from the “react-dom.js” file.

Ultimately, embedding the library with script tags is the most familiar and straight-forward option, but it’s also limiting. We can’t install packages from the npm repository, which we’re going to do be doing later on, and we miss out on certain features, such as automatic page reloads while we’re making changes to our code. This option is great for the sake of utmost simplicity, but it will be a little too simple for our purposes.

Option #2: JSBin / CodePen / JSFiddle

All of these tools are the fastest way to start experimenting with React, but they just provide you with the embedded version of the library, so they suffer from the same limitations as the previous option.

In the case of JSBin, this is the setup process for working with React:

  1. Click the “JavaScript” drop-down menu.
  2. Select the “JSX (React)” option.

You’ll notice that the React library is automatically embedded at the bottom of the “HTML” pane on the left side of the screen.

Jsbin setup

It’s not a great option for developing a complete interface – for dealing with a lot of code, a traditional text editor is a lot more practical – but it’s nevertheless useful for playing around as a beginning developer.

Option #3: Building with Webpack

The most advanced way to develop with React is to setup a project with Webpack. If you don’t know what Webpack is, that’s fine. It’s a topic for another day (and perhaps another book). For the curious though, Webpack is a “module bundler”. It allows us to create a React application across a number of files and then bundle those files together into a single JavaScript file.

Additionally, Webpack can be used to:

  • Import packages from the npm repository into our React projects.
  • Process our project’s files in a variety of ways, such as checking the code for errors, giving us early access to upcoming JavaScript features, or minifying the final output for better performance.
  • Launch a local development server with “live reload” functionality, which will automatically refresh our application in the browser as we make changes to the code.

Sooner or later, it’s a good idea to become familiar with Webpack, but it’s not necessary to be familiar with it throughout the course of this book.

Option #4: create-react-app

To help people get started with React, the developers of the library put together “create-react-app” – a command line application for quickly creating and managing React projects.

Here’s the gist of how it works:

  1. You run a command to create a React project.
  2. All of the necessary files are created for you.
  3. You start developing without any other setup.

Behind the scenes, create-react-app relies on Webpack, so it doesn’t actually do anything we couldn’t do ourselves. Nevertheless, it’s a solid boilerplate that allows us to get up and running with React in a matter of minutes, while still providing enough power and flexibility to build something interesting.

The only side-effect of using create-react-app is that you won’t be able to customize your Webpack configuration, which can be necessary further down the line. But that’s not something we have to worry about at this point, so it’s a non-issue for the time being.

Note: You’re never actually locked into create-react-app. If you need extra configuration power, you can always “eject” your project out of it, so starting a project with it will never leave you trapped.

Ultimately, create-react-app is an excellent choice for creating interfaces with React, as it provides the perfect blend of power and simplicity, and it’s what we’ll be using throughout the rest of this book.

Installing React, Part 2

In this section, we’re going to install everything we need to create our first React project. This includes Node, create-react-app, and a Google Chrome extension known as React DevTools.

Step #1: Install Node

If you’re a JavaScript developer, there’s a very good chance you already have Node installed on your system. If not, you will need to install it, as it’s required to use the create-react-app command line application.

To download and install Node, visit nodejs.org/en/download/. It’s available for all major operating systems and the installation process is just a matter of running an executable.

Download node

Step #2: Install create-react-app

To install create-react-app, we need to run a command via the command line, but the command line will have a different name depending on your operating system:

  • If you’re a macOS user, the command line application is “Terminal”.
  • If you’re a Windows user, the command line application is “Command Prompt”.
  • If you’re a Linux user, the command line application will depend on what distribution you have installed.

After opening the relevant application, type the following command:

npm install create-react-app --global

Then tap the “Return” key.

Install create react app

Here, we’re using this npm install command, which became available to us after we installed Node, and we’re using this command to download and install “create-react-app” from the npm repository.

The --global option allows us to run create-react-app commands from anywhere on the computer, rather than from just inside a single folder. Don’t forget to include it.

It’s worth noting that, if the installation fails, it’s probably because you need administrator permissions to execute the command. If that’s the case, try the command again with the sudo keyword at the start of the line:

sudo npm install create-react-app --global

After tapping the “Return” key, you’ll be asked for your password, and once that’s entered, the application should download and install.

Step #3: Install React DevTools

Throughout this book, we’re going to be using React DevTools – a browser extension that is similar to the “Inspector” feature that’s found in Chrome and Firefox, except that it’s designed for React applications.

React devtools

We don’t need React DevTools to develop with React, but the extension is extremely useful for learning and debugging, so we’re going to keep coming back to it as we delve into various React concepts.

You can download the extension for either Google Chrome or Firefox.

Project Setup

Before we create our first React project, let’s create a folder to keep all of our React projects in the same place. We don’t have to do this, but it’s a good way to keep our code organized.

Inside the command line, run the following command:

mkdir React

This mkdir command stands for “make directory”, and as you can likely guess from the name it allows us to make a directory.

In this case, we’re making a directory named “React”.

Mkdir react

The exact location where this directory will be created will depend on your operating system, but at least on macOS, the directory will appear inside the “Home” directory. (If you’re on a different operating system, you may have to search your computer to find it.)

To navigate into this “React” directory, use the cd command:

cd React

This cd command stands for “change directory”, and after running it, we’ll be inside the “React” directory we created a moment ago.

To create a React project within this directory, run the following command:

create-react-app leaderboard

Here, this command has two parts:

  • create-react-app is the command we use to create a React project
  • “leaderboard” is the name we’re assigning to this project.

You’re welcome to name the project however you like, but it’s a good idea to avoid using spaces or special characters within the name.

Running create react app

After tapping the “Return” key, create-react-app will:

  1. Create a package.json file, which contains our project’s configuration. This file is not specific to React, but rather exists within any project that depends on packages from the npm repository.
  2. Download all of the npm packages that React relies upon. This is the part of the setup process that takes the most time.
  3. Create a basic project structure with boilerplate code that acts as a useful starting point for the majority of React projects.

In a moment, we’re going to delete a number of files that create-react-app created for us, as it’s more insightful if we start from scratch, but before we do that, let’s take a brief tour of everything that was generated.

Project Structure

This is the default file structure of a React project that’s generated by create-react-app:

  • node_modules/
  • public/
  • src/
  • package.json
  • README.md
  • yarn.lock

The good news is, we can ignore most of these files and folders. In fact, we’re only going to be working with the “public” and “src” directories. But it’s still useful to have a basic idea of what everything is doing.

Default file structure

yarn.lock

README.md

By default, this file contains the documentation for the create-react-app tool. You don’t need to read this documentation, as we’re going to cover the important bits in this book anyway, but it’s well-written and contains more detail than what we’re going to discuss, so you may like to read it later down the line. You can find the same documentation on GitHub.

package.json

Whenever a project relies on packages from the npm repository, we use a file named “package.json” to keep track of those packages, and whenever we use the create-react-app command, the following “package.json” file is automatically generated for us:

{
  "name": "leaderboard",
  "version": "0.1.0",
  "private": true,
  "devDependencies": {
    "react-scripts": "0.7.0"
  },
  "dependencies": {
    "react": "^15.4.1",
    "react-dom": "^15.4.1"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  }
}

The first three options are standard meta-data for a “package.json” file:

  • “name” defines the name of the project
  • “version” defines the version number of the project
  • “private” can be set to true to ensure that the project is never published to the npm repository

The next two options are where we define what packages the project depends on:

  • “devDependencies” defines what packages are only needed during development
  • “dependencies” defines what packages are needed at all times

Nested within the “devDependencies” option is the “react-scripts” package. This package is a container for a number of other packages, including:

  • webpack (with webpack-dev-server, html-webpack-plugin, and style-loader)
  • Babel with ES6 and extensions used by Facebook
  • Autoprefixer
  • ESLint
  • Jest

You don’t have to understand what any of these packages do. It’s just worth noting that, if we wanted to, we could create an empty “package.json” file, install the “react-scripts” package, and have access to most of the features that create-react-app provides us with. The only reason we don’t do that is because it’s faster to use the create-react-app command.

React scripts package

Within the “dependencies” option, there’s a “react” and “react-dom” package, which correlate with the JavaScript files we discussed earlier:

<script src="https://unpkg.com/react@15/dist/react.js"></script>
<script src="https://unpkg.com/react-dom@15/dist/react-dom.js"></script>

The “react” package contains the core React library, while the “react-dom” package contains the parts of React that are specific to web development.

At the bottom of the file is the “scripts” option, which is where we can define certain scripts that we want to execute when we run commands in the command line.

In this case, create-react-app has four default commands:

  • start to launch a development server, which is what we’ll use to play around with our application as we’re developing it
  • build to bundle all of the JavaScript files into a single file, which is useful for deploying the application to the web
  • test to run test against our code
  • eject to “free” the project from create-react-app, which is necessary if you’d like to use a custom Webpack configuration

Each of these commands are associated with commands from the “react-scripts” package, meaning these commands:

npm start
npm build
npm test
npm eject

…are shortcuts for these commands:

react-scripts start
react-scripts build
react-scripts test --env=jsdom
react-scripts eject

In this book though, we’re only going to be using the start and build commands.

src/

The majority of any project’s code will be placed inside the “src” directory. This includes both JavaScript and CSS files. There are many different ways we can structure the files within the “src” directory, but there’s no strict structure that we have to follow. In fact, the default structure doesn’t use any sub-directories. There’s just the following files:

  • App.css
  • App.js
  • App.test.js
  • index.css
  • index.js
  • logo.svg

But we’re going to delete these files in a moment, so there’s no need to look through them.

public/

When we eventually run the npm build command, a new directory named “build” will be created that contains the final output of our project, and the significant thing about the “public” directory is that anything inside this directory will be coped into the “build” directory without any further processing. In our case, we’ll only have an “index.html” file inside this directory, but any files that never need to be processed (such as a logo, for instance) can be placed in here.

node_modules/

When we install packages from the npm repository, those packages are stored in this “node_modules” directory. You should never need to play around with this directory, but if you look inside of it, you’ll see the packages we’ve already installed, such as “react” and “react-dom”.

Local Server

It’d be extremely annoying if we had to run the npm build command every time we wanted to see the results of whatever code we were writing. Fortunately, we don’t have to do this. Instead, we can use a local development server.

A local development server allows us to preview our project in the browser, and whenever we make changes to the code, the browser will refresh the page to reflect those changes.

To use the local development server that’s included with create-react-app, return to the command line and navigate into the “leaderboard” directory:

cd leaderboard

Then run the npm start command:

npm start

The following output should appear in the command line:

Compiled successfully!

The app is running at:

http://localhost:3000/

Note that the development build is not optimized.
To create a production build, use npm run build.

…and a browser window should automatically open with the default React project that’s generated by the create-react-app command.

Default react project

If the browser window doesn’t automatically open, that’s fine. Just open your browser of choice and visit the following address:

http://localhost:3000

If, at any point, you’d like to stop the local development server, either quit out of the command line or tap the CTRL + C keyboard shortcut while the command line is in focus. For the purposes of this book though, we’re going to need the local server to be running, so it’s best if you just leave the command line open in the background.

To end this section, delete all of the files inside the “src” and “public” directories. These files make up what we currently see in the browser but we won’t need them in the coming chapters.

Finally, we’re ready to write some code.