
Using Create React App to Create Our Project
It's finally time to roll up our sleeves and get to work. You should have a very thorough understanding of Create React App's offerings, but now it's time to actually put that understanding to use.
Again, remember that Create React App creates a project for us, and that includes a lot of extras that act as the main scaffolding for our project. Much like a painter's scaffold, from far away it can seem like a lot of things have been added just to begin working, but the beauty is that it is all work that we would have to do anyway. This allows us to bypass that step and go right into getting some work done!
We will create our first project, which we will call hello-react, by running the following command:
$ npx create-react-app hello-react
The output will be as follows(truncated output):
npx: installed 91 in 23.129s
Creating a new React app in /home/brandon/code/hello-react.
Installing packages. This might take a couple of minutes.
Installing react, react-dom, and react-scripts...
…
├─ react@16.10.2
└─ scheduler@0.16.2
Done in 151.99s.
Done in 49.76s.
Initialized a git repository.
Success! Created hello-react at /Users/brandon.richey/Development/react-book-2/chapter1/code/hello-react
Inside that directory, you can run several commands:
yarn start
Starts the development server.
yarn build
Bundles the app into static files for production.
yarn test
Starts the test runner.
yarn eject
Removes this tool and copies build dependencies, configuration files and scripts into the app directory. If you do this, you can't go back.
We suggest that you begin by typing:
cd hello-react
yarn start
Happy hacking!
This will give us our initial project, scaffolding and all, and allow us to jump right into coding.
Before we do that, we can see the output from our npx create-react-app command that tells us some of the other scripts we can run via yarn: start, build, test, and eject. We will be using start, build, and test the most, so we will focus on those and skip eject for now.
Each of the commands is broken down into a very specific and common scenario of application development and maintenance:
- start spins up a server listening locally on your computer on a specific port, where it watches for any changes made in the project, and then, when those changes are made and saved to the filesystem, it automatically reloads the appropriate project files. This gives you the ability to see changes that you make in your code as you save each file and make tweaks and modifications as necessary along the way. This is something that by itself could take a lot of time and effort to set up, so we are using Create React App just to avoid having to do this every time. Almost immediately, this makes the app scaffold worth it.
- Next, we have build, which is used to produce an optimized production build of our code. This takes all of the project's code (not just the JavaScript, but other file types, such as CSS) and optimizes as much as possible for use in a production environment. This includes minification (the process of stripping code files down to be as small as they possibly can be) and any other major optimizations that allow the code to download faster and execute quicker when it's out and serving real production traffic.
- Finally, of the most common commands, we have test. Now, test will run all of the tests for your code and display the results in an easy-to-read manner. It will also automatically run unit tests for each code change, including just the tests that failed when related code was modified, resulting in a broken test suite.
- eject is not often used but is invaluable when you start hitting certain limitations of the Create React App scaffold. eject is a command that pulls the covers off all of the configuration and scripts behind the scenes in your project, allowing you to edit and tweak any configuration detail that you will like. This also removes the safety net of the scaffolding, so it becomes easier to accidentally change something in your project and potentially break things or negatively impact the reliability of your production builds. Also, when you run this command, there is no turning back, so this is definitely something that you only want to do when you are good and ready and understand the potential impact on your project.
Now, let's start exploring the crated project.
Exploring the Created Project
We have run the command to generate our project, but now it's time to take a deeper look and understand a little more of the scaffold and what we have been provided with. Here is an example of the files that are automatically generated in a new project:

Figure 1.5: Files generated in a new react project
We will start off by just exploring the top levels and then look more closely at any noteworthy inpidual files along the way. You'll find that even the starter project includes quite a few files, and while we will not go into extreme detail on each inpidual file, we will talk a little bit about how they all fit together overall.
README.md
The first notable file, right in the project root, is our README.md file. This is a markdown file that tells people how to use and interact with your project. Usually, this should include instructions, a brief synopsis of the project, how to start the project, how to run the tests, and any additional dependencies or common catches that someone will need to know to use the code base you have created. Think of this as the first official piece of documentation for the project that you are building.
Deep pe: package.json
The next notable file in the root directory is the package.json file. package.json exists to tell Node.js more details about this project. This could be anything from metadata about the project (name, description, author, and more) to dependency lists.
Let's take a look at a sample generated package file:
package.json
1 {
2 "name": "hello-react",
3 "version": "0.1.0",
4 "private": true,
5 "dependencies": {
6 "react": "^16.8.6",
7 "react-dom": "^16.8.6",
8 "react-scripts": "3.0.1"
9 },
The complete code can be found here: https://packt.live/2y121qR
Here, we have some notable keys and some more metadata-style keys combined together:
- We have a name key, which is basically just the name of your project itself.
- Next, we have the version, which should be used to indicate the semantic versioning for your project.
Note
Semantic versioning is a numbering system used for a large number of software projects. It typically follows a numbering scheme where the numbers, separated by periods, indicate the major version, the minor version, and the patch version. In our example, 0.10.0 indicates a major version of 0, a minor version of 10, and a patch version of 0. The major version is used for major rewrites or backward compatibility-breaking changes, the minor version is used for large changes that may not dramatically affect backward compatibility, and the patch version is typically used for tiny fixes, usually hotfixes or security updates, that don't affect backward compatibility at all.
- We also see a private flag, which tells npm (our package and dependency management system when using Create React App) if our project is public or private. If it is private, then it is not published to npm with any sort of public visibility.
Note
When private is set to false, the project instead gets public visibility.
- Moving on, we have our dependencies section. The dependencies list is critical to your project, as this is what is used to tell Node.js what other libraries your project depends on. This could be major dependencies, such as React in our example, or sometimes less critical sets of dependencies such as utilities to make writing your tests a little easier. Here's the dependencies section of our example:
"dependencies": {
"react": "^16.8.6",
"react-dom": "^16.8.6",
"react-scripts": "3.0.1"
},
If you look at our dependencies list, you'll just see three entries in there: react, react-dom, and react-scripts. Each of those dependencies includes their own sets of dependencies, and in the case of react-scripts, a lot of those dependencies are related to the functionality for example, live changes of development server, auto reload of those changes. Create React App provides functionalities which are found in one of those tucked-away dependencies.
- Next, we have our list of scripts:
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
}
These are commands that you can run via npm or yarn. Create React App provides the four that we have already talked about: start, build, test, and eject. Each of these can be executed either via npm run [script] or yarn [script]. If you wanted to add your own (for example, you can add something like a clean script to clean out temporary files during development and testing), you would just add it there.
- Moving on, we have our eslintConfig setting, which tells our code linter to use create-react-app style linting:
"eslintConfig": {
"extends": "react-app"
},
Note
Code linting is the process of looking through the code files in your project and highlighting things that may violate best practices, either for security or developer sanity. You may find things such as whitespace violations, problems with naming conventions, or a myriad of other possible things to highlight and warn against. This is a great thing to include in your project (or alternatively, you can use something like Prettier, an automatic code formatter, instead).
- We also have browserslist, which tells Create React App which browsers to target for our projects to work with:
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
The list is broken down into two subsections that specify for the build process whether we should be building things for production or for development. These are relatively sane defaults and don't tend to be modified or tweaked very often.
We have a pretty good idea of the package.json file and its contents, so we can safely move on to exploring the rest of the scaffold.
Note
yarn and npm are two different package managers in the JavaScript world. yarn sits on top of npm and installs npm packages. However, yarn manages its dependencies differently and adds those dependencies to your project differently than npm typically does. These are almost entirely internal differences that you typically do not need to think about during the build process, but that is why you see both yarn and npm dependencies listed in your Create React App project.
Exploring the Rest of the Scaffold
yarn.lock provides a way to lock in the dependencies of our project, preventing a scenario where major changes might be introduced in the production stage due to an upgrade to the library version.
We also have a hidden file hanging out in our scaffold, .gitignore. The .gitignore file tells Git what files to ignore when you are committing to avoid them showing up when other people clone or fork your repository. Typically, you will use this to hide files that contain any sort of secrets or keys, or anything else that you don't want committed into the project's repository (node_modules, for example, is typically ignored).
We also have the node_modules directory, which stores all of the Node.js dependencies for your project; everything your project needs to run will go here. create-react-app has a lot of dependencies that are included for running the project for different environments and settings that allow you to use the latest and greatest in JavaScript syntax additions. This is typically ignored from committing to the code base via an entry in .gitignore (more on that later).
There is the public directory, which includes all the files that you will want to interact with after the build process is completed. This is a good place to put certain types of assets, such as images, movies, or any kind of documents or downloads you'd want to include in your project. For example, our favicon.ico file would be found here, along with an index.html file, which is used to pull in the built application when served from that directory, and the manifest.json file, which is used to describe Progressive Web Apps. Progressive Web Apps are apps that can be downloaded and used offline as well and may have faster startup times if cached appropriately by your browser.
Finally, we have the directory we are going to spend the most time in: src. Now, src contains all of your actual application code. All your React code will be located here, which is then built and output into public/ after being combined, minified, and turned into files that make it easier for the browser to download, consume, and interpret the project you have built, all in the name of further optimization.
With all this knowledge, we need to now understand how to code an element or a component of a web page in React.