React Quick Setup

Chapter 3 30 mins

Learning outcomes:

  1. Calling in external <script>s
  2. Using Create React App

Introduction

In the previous chapter, React Prerequisites, we talked about the necessary concepts to know before one can begin his/her React journey. It touched upon very important ideas such as let and const; arrow functions; destructuring; closures; reflow and repaint; and much more.

Now we're almost ready to start writing React. Yup, almost.

In this chapter, we'll see how to set up the entire environment for writing and executing React in Visual Studio Code. Specifically, we'll be unravelling three different approaches to get started.

One is the quick way, using third-party <script>s, which will get you started in almost no time' the second one is also fairly straightforward, using a ready-made toolchain called Create React App; and the third one is a bit more complex, manually configuring a module bundler, Rollup in this case, to run React.

There is a lot to learn in this chapter, so let's dive right in without any further ado.

Calling in external <script>s

The quickest way to get started with React is to spin up an HTML document and bring in external CDN libraries, accessible from unpkg, via a couple of <script> elements.

At the very minimum, two libraries are required. One library is for React itself (the core), while the other is for React DOM (the rendering library of React for the browser).

With this approach, we don't have to install literally anything on our end to get started with React.

Here's how this works.

Let's say we have the following barebones HTML page:

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>Learning React</title>
</head>
<body>

</body>
</html>

To get started with React in this way, we just need to bring in two external <script>s from unpkg, as illustrated below:

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>Learning React</title>

<script src="https://unpkg.com/react@18/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js" crossorigin></script> </head> <body> </body> </html>

With these scripts in place, we can now go on and include a <script> element in <body>, right at the end, where our actual React code will eventually go:

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>Learning React</title>

   <script src="https://unpkg.com/react@18/umd/react.development.js" crossorigin></script>
   <script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js" crossorigin></script>
</head>
<body>
<script>
// React code goes here.
</script> </body> </html>

The reason for putting this <script> element at the end in <body> for now is just so that if we want to select any DOM nodes from the HTML document, we have access to it in the <script>.

If we were to instead put the <script> tag in the <head> section (obviously still after the preceding two <script> tags), then we won't have access to the <body> element, let alone having access to any element inside <body>!

So far, so good.

Although the code above is precisely all that is required to run React, it is NOT enough to be able to parse JSX in our React code. So what is JSX?

While we won't be going into a lot of depth regarding JSX right now, for that depth is covered in the chapter React JSX, a little knowledge will allow us to better understand the next library that we call in on our HTML document.

JSX stands for JavaScript XML. It's an extension of JavaScript that resembles XML (or in simpler words, HTML), created by the same team behind React in order to make writing React code highly intuitive.

As an example, here's some React code (actually just JavaScript code) without JSX. It defines an <article> element with an <h1> inside it:

let element = React.createElement(
   'article',
   null,
   React.createElement('h1', null, 'Hello World!')
);

Assuming you're well-versed with JavaScript, you shouldn't have a hard time making a very rough sense of what this code is doing. Don't worry if you don't understand the exact details right now; those will be covered in the next-to-next chapter.

Now, here's the same code, albeit in JSX:

let element = (
   <article>
      <h1>Hello World!</h1>
   </article>
);

See how we've expressed the desired HTML right in the JavaScript, thanks to JSX.

But wait. That's completely invalid, illegal, gibberish JavaScript! Isn't it?

Well, it sure is. JSX is NOT valid JavaScript!

The problem with JSX is that it can't be understood by browsers — it's purely a syntactic innovation to be able to intuitively work with React. We can't go on and write JSX inside the last <script> element in our HTML document above without anything else, hoping that it would work; it just won't work!

To get JSX code written in a <script> to be executed by the browser, we have to use another program that itself runs in the browser and is capable of understanding and executing the JSX code we write. The browser itself never reads or executes the <script>.

Babel is such a program.

Babel is a JavaScript transpiler and a runtime engine (written in JavaScript itself).

The term 'runtime engine' here is of interest to us. It states that Babel can be used to run a JavaScript program from within the browser; we just need to provide it with the text representing the source code of the program.

Babel is capable enough to parse many modern features and innovations of JavaScript, including JSX, TypeScript and the beta features of ECMAScript (sometimes referred to as ESNext).

Akin to React (core) and React DOM, Babel is also available as an external library at unpkg, which means that we could easily bring it into our HTML via a <script>.

Let's go ahead and refer to the Babel library in our HTML page:

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>Learning React</title>

   <script src="https://unpkg.com/react@18/umd/react.development.js" crossorigin></script>
   <script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js" crossorigin></script>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script> </head> <body> <script> // React code goes here. </script> </body> </html>

And we're done, right? Well, not now.

As stated before, JSX can't be understood by a web browser. If we continue with the setup above as it is, the <script> inside <body>, which is meant to contain our React code expressed in JSX, will get executed just like any other <script>. But since a browser can't understand JSX, this will lead to an error.

Yes, Babel has been brought in and is running, but it doesn't have control over being able to prevent this script from running. We have to explicitly instruct the browser NOT to execute the last <script> ourselves.

And that's typically done by adding a type attribute to the <script> whose value is not recognizable by the browser. This is a behavior common to all browsers wherein when they encounter a <script> with an unknown type, they don't execute it.

Coming back to Babel, it specifically says to set the type of the script that it should be executing to "text/babel". In this way, the Babel program is able to detect which <script> it needs to execute and which not.

Once the document loads, Babel goes over all <script>s in there and checks each one's type attribute (which can very easily be done using DOM methods). If the type is equal to "text/babel", Babel parses and executes that <script>.

Below, we make this desired change in our HTML page:

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>Learning React</title>

   <script src="https://unpkg.com/react@18/umd/react.development.js" crossorigin></script>
   <script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js" crossorigin></script>
   <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
</head>
<body>
<script type="text/babel"> // React code goes here. </script> </body> </html>

And this is it for the most straightforward way of getting started with React.

If you want to, you could skip the following sections and move over to the next-to-next chapter, getting on track to writing your very first React program.

However, almost NO one develops applications this way.

It might suffice as a quick way to get started with React, but in the longer run, it's not going to be scalable, maintainable or effective. It's not even resource-wise efficient for production.

The problem with calling Babel at runtime

Everytime we refresh the webpage, the Babel program has to reparse our entire React code and only then be able to execute it. If our code doesn't change, this can be wasteful.

Moreover, if the code is extremely huge — think of something of the scale of Facebook or Spotify — then it could take some time to parse and execute it. That time might just be milliseconds, but in today's modern era, even a single millisecond matters, especially if we know that we could easily improve upon that.

And even if time isn't a concern somehow, such an approach is always bound to waste to resources. Ideally, the parsing of the code should happen once and then the result be used again and again. Not only does this prevent the wastage of resources but also gives a boost to speed.

So then what?

Well, as is the norm, we'll set up a local environment to work with React that allows us to easily manage complex React projects for both development and production, and also solves the problem discussed above of running Babel directly in the browser.

The following discussion is devoted to understanding this setup.

Using Create React App

Create React App is a pretty handy tool created by Facebook (the same entity behind React) in order to easen the tidy process of setting up an environment to develop React applications.

Create React App, or simply just CRA, allows us to bootstrap a complete React application on just one single command in the terminal.

CRA belongs to a set of tools that are commonly known as scaffolding tools.

Scaffolding simply means to prepare the whole ground for building a project, with preconfigured settings, directories, files, and much more. It saves us a considerable amount of time otherwise spent in manually doing all of this, and helps us start off with a conventional, well-tested, and intuitive project structure.

CRA frees us from the worry of having to manually install each and every tool otherwise required in a React application (such as a transpiler, a bundler, a linter, etc.) and then configure that tool according to our needs; it handles everything very nicely on its own.

Let's see how to set up a development environment for building React apps using CRA.

Before we begin, however, it's worthwhile noting that you'll need to have Node.js installed on your computer.

Why is Node.js required for developing a React application?

Although we won't be directly using Node.js for developing React apps, it is required for two reasons:

  • To install the tools that power React application development. In one way or the other, this involves the package manager, npm, that comes along with Node.js.
  • To drive the logic used by those tools (for e.g. interacting with the local filesystem).

As a quick example, as you'll soon see in this course, when we're developing a React application, it's customarily broken down into individual modules (i.e. files). These modules are brought together into a single, bundled file, when the React application is prepared for a production build (i.e. to be deployed to a live website).

But how are the files read in the first place?

As we know, JavaScript (in the sense of frontend) can't be used to read files on the local filesystem. And that's exactly where Node.js enters the game.

A tool called a bundler is used by every single React toolchain (like CRA) in order to accomplish this task, and it internally relies on filesystem functionalities provided by Node.js to interact with local files.

Beyond this stage, we assume that you have Node.js completely set up on your computer.

Let's turn to business.

The following steps apply to Windows, but the steps should more or less be replicable on any other operating system as well.

  1. Run create-react-app

    First off, open up a terminal window and change the current working directory to where you want CRA to create a new React project (which is also a directory).

    In our case, since we want to create a new project under Desktop, we'll open up Desktop in the terminal.

    Here's how the terminal looks:

    ...\Desktop>

    Notice the input prompt displaying the current working directory.

    Now, we need to use CRA to scaffold a new React project in Desktop. The CRA tool is called create-react-app in npm.

    Pretty simple name, isn't it?

    The name of the directory representing the project is provided to create-react-app as an argument in the terminal. We'll name our project react-course.

    Go on and enter the following command in the terminal:

    ...\Desktop> npx create-react-app react-course

    This command will begin the tedious and most important process of setting up a React project, installing all the required tools and preconfiguring them.

    What is npx?

    You might be wondering what exactly is npx in the command above, were you?

    npx is an executor of npm packages that comes along with a standard Node.js installation. It saves us from having to locally install a tool from npm before being able to use it — it automatically pulls in the latest version of the tool from npm and executes it in situ.

    We're using npx with create-react-app in order to use the latest version of the CRA tool. This is even recommended by the official documentation of CRA.

    Keep in mind that it'll take some time for the command to complete as there is a host of tools and libraries to be downloaded and installed.

    Once complete, the terminal will display a large blob of text describing the most important stages of the installation process, and then in the end, describing how to work in the created project.

    Something like the following:

    ...\Desktop> npx create-react-app react-course
    Installing packages. This might take a couple of minutes. Installing react, react-dom, and react-scripts with cra-template... ... We suggest that you begin by typing: cd react-course npm start Happy hacking!

    With this done, now it's time to get into the project using Visual Studio Code.

    CRA adds a lot of stuff!

    As you'll find out, CRA tends to add a lot of stuff to a project — like literally, a lot of it — most of which isn't required by most developers, and for that reason many people don't like it.

    Still, it's better to try a tool to the full before building an opinion about it.

    We encourage you to try CRA, and then even try the manual setup process we share below using Rollup, and only then build your preference between them.

  2. Create a workspace in VS Code

    Once the react-course directory is created, we need to open it up in Visual Studio Code as a new workspace. A workspace is basically a directory holding all the work of a project.

    To open up a directory as a workspace, launch Visual Studio Code, and then from the Get Started window that shows up, select the Open Folder link. This will open up a file browser panel. From here, locate the react-course directory that you just created and then open it up.

    This should create the directory as a new workspace in VS Code, ready to be worked with.

    Let's move to the next step.

  3. Getting familiar with the setup

    At this stage, your VS Code window should look something as follows, with the react-course directory loaded up in the left sidebar.

    react-course directory loaded up as a VS Code workspace.
    react-course directory loaded up as a VS Code workspace.

    Now, let's get familiar with a couple of things in here. We won't go into a lot of detail because that would otherwise elongate the length of this chapter. If you want to learn about every single file that comes with a CRA-created project, head over to this article.

    In particular, for now, we'll just be going over the src directory, where we'll be writing our React code.

    Here's how the src directory looks:

    The src directory in a CRA-created project.
    The src directory in a CRA-created project.

    For now, we don't need anything here except for the index.js file where we'll begin writing our React program in the next React First Program chapter.

    Henceforth, go on and delete all the files (by selecting them and pressing Delete), leaving only the index.js file.

    Here's how the src directory should look in the end:

    The src directory after deleting files.
    The src directory after deleting files.

    After this, open up the index.js file and clear up all the code that's inside it, for we'll be starting to code in it from scratch in the next React First Program chapter.

    index.js file cleared up.
    index.js file cleared up.
  4. Trying running npm start

    Open up the terminal again, and enter the following command in order to launch the React app in the browser:

    ...\Desktop> npm start

    It might take a couple of seconds for it to complete, before automatically opening up a browser window and navigating it to localhost:3000, where our React app is served.

    Obviously, since our index.js file is empty, we'll get no output in the browser. This step is only to get a hands-on experience of the command that we'll be eventually leveraging in the upcoming chapters to launch our React apps.

  5. And this is all about setting up our first React project using Create React App. The actual coding will commence in the next-to-next chapter.

    If you want to read about how to manually set up a React development environment without using CRA, continue on reading the next chapter, where we talk about such things as Babel, Rollup, react, react-dom, etc. that come together to form a development environment for working in React.

    But if you don't want to read further, for now, you're all good to start off with the next-to-next chapter, where we create our very first program in React.