Home Web Development Create React App 2 Quick Start Guide

Create React App 2 Quick Start Guide

By Brandon Richey
books-svg-icon Book
eBook $22.99 $15.99
Print $32.99
Subscription $15.99 $10 p/m for three months
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
eBook $22.99 $15.99
Print $32.99
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
About this book
If you're a power user and you aren’t happy always reusing default configurations, from previous applications with each new application, then all you need is Create React App (CRA), a tool in the React ecosystem designed to help you create boilerplate code for building a web frontend. This book will help you use CRA to write React programs without significant configuration-related difficulties. With this quick start guide, you will integrate your applications with React to build efficient professional web services.You will learn to design UIs with the features of CRA and template your React applications. By the end of the book, you will be sufficiently skilled to be able to build faster and effective React apps using CRA.
Publication date:
February 2019
Publisher
Packt
Pages
188
ISBN
9781789952766

 

Introducing Create React App 2

This book will be a guide on how to effectively use Create React App 2 (CRA) to create a new React project and build the web project of your dreams! We will cover many topics, including how to install Create React App, the project structure you get by default, and how to add code and libraries to your project. We will explore everything you'll need to be able to build complex, modern web applications using the latest and greatest of the most common React project configurations and compilations.

To be able to do this however, we first need to take a little time to talk about the project itself, its humble beginnings, and what problems it is ultimately attempting to solve. By understanding the history and the intention, we can better understand how to take full advantage of the toolset we are provided and also understand where and why limitations exist.

In this chapter, we'll discuss what Create React App is and what it brings to the table. By the time you're done with this chapter, you'll understand why Create React App is so important and how it helps the developer get more done in less time overall. We'll also discuss what topics the book will cover, the format itself, and how to best follow along.

In this chapter we will be looking at the following topics:

  • Starting a new Create React App project
  • The commands for starting and stopping your server
  • The commands for running tests
  • The commands for creating production-ready builds
  • The commands for exiting the Create React App confines to further tune and configure your project

 

What is Create React App?

A lot of different programming languages, tools, and frameworks have a number of different ways to jumpstart development for their particular toolset. Sometimes this requires downloading a bunch of libraries, or getting started with a pre-built binary file or compressed archive for the right architecture, operating system, or other configurations. Sometimes it has a nice pre-built pathway to get started in a way that minimizes frustration but potentially limits available options.

The trouble, however, is that with a lot of JavaScript frameworks, there was not a similar option. Getting started using any particular framework or technology was actually a markedly difficult problem to solve, due to differing combinations of every person's skill set, operating system, and task.

Create React App is JavaScript 's answer to the getting started toolset that did not exist in any particularly approachable way. Generally speaking, to get started with a project, you'd have to learn a large number of supporting technologies and techniques before you could really get moving. You'd have to know a configuration framework, such as Babel, Webpack, Brunch, or Gulp. As well, you would have to know how to get a project structure going in JavaScript. After you've figured everything else out, you'd have to learn how to set up a development server that auto-reloads changes on the fly. After all of that, you still have to figure out how to set up your testing framework, React, and any additional libraries you want.

This ends up being a huge amount of effort, and that's just to get started. It's compounded by the fact that every single piece of framework and configuration that you're developing expertise with might not transfer into your next job!

Instead, Create React App aims to do something different: make configuration and setup a one-step process. This allows you to focus on getting started and building your application earlier, and worry about the more in-depth portions of work later. You can focus more time on writing your code and less time on configuring a great development environment. Your environment in a Create React App application will already be a great development environment, and that's a fantastic removal of barriers and obstacles for developers, both new and seasoned!

The Command-line interface (CLI) tool provides a great development environment that encourages rapid iteration and test-driven techniques. We have a lot of the configuration and specific libraries figured out for us so we don't have to do that legwork. Moreover, you're never locked in to any choices you make. The Create React App team included an eject option that pulls the entirety of the application you've been developing and turns it into a standard webpack or babel build, for example, that can be plugged into anything compatible with Node Package Manager (NPM). You don't have to be worried about having to duplicate a huge amount of effort to transfer your code from Create React App to your own project or a specific environment configuration and setup at your job; you can just make something that transfers nicely, safely, and cleanly. You can even tweak the configuration at this step (after ejection) and further make this application your own!

What is the history of Create React App?

To better understand where Create React App succeeds, we have to understand where the JavaScript development world started. We need to see the warts of the system to know why certain things were fixed and how they were fixed. Let's talk a little bit about the history of JavaScript development and some of the main issues that developers were running into frequently!

The early days of JavaScript development

To start, you need to dive back into the past of dealing with JavaScript code in the frontend. For a long time, you would end up with these JavaScript files that you'd just download off of a content delivery network (CDN) somewhere, throw into your frontend code, write a bunch of extra JavaScript code in front of that, and call it a day.

This was nice in the sense that you had your dependencies locked down to whatever version you downloaded and stuck on the server, and whatever you deployed was pretty easy to develop against because all of the dependencies were already there and ready to go. Unfortunately, it introduced a ton of problems in many other ways. For one, you would run into issues constantly where one of the libraries you downloaded was completely incompatible with a specific version of one of the specific versions of another library, and often that was a complex and difficult process. The way most people solved that problem was divided into a few camps:

  • Going through and finding all of the incompatibilities and fixing them
  • Writing complex glue code that would make the libraries behave together by wrapping one of the libraries and providing a means for the two libraries to work together
  • Downloading a different version of the library just for another library and storing them separately, resulting in giant JavaScript bundles when you load the web page because you're probably downloading two to three different versions of something, such as jQuery
Yes, that last bullet point is a real thing that real developers did! You can probably see why this is something developers tried to move away from as soon as they could.

The bundle era

To solve this problem, it was important to solve the dependency problem in general. The move toward Node.js-based tools, such as npm, helped significantly, because now your dependencies would be pulled from a centralized location and versioning became a first-class citizen of JavaScript development, which was fantastic!

What was less fantastic, however, was when you needed to apply this problem to browser code and rich web applications. Often, this meant an intricate dance of understanding what libraries were required for which projects. If you wanted to use React with JSX (we'll talk more about this later), as well as the latest JavaScript syntax, you needed to know exactly what versions of React and Babel to include. You'd also need to understand which Babel plugins you'd need to have to support your use of whatever draft of JavaScript syntax.

Do you want to use some CSS transformers or any other language help, such as TypeScript or Flow, in your React project? If so, building and configuring your project becomes markedly more difficult, and we haven't even gotten to the problem of getting this code put together to be used on the browser! Now you needed to have a wide breadth of knowledge just to get your project started, and a wide depth of knowledge for knowing how to set up and configure something such as Webpack, Bundler, Grunt, Gulp, or Brunch!

This is the point of development that we were in before the prevalence of command-line tools and configuration utilities, so let's dive into that by talking about what problems Create React App solves!

What problems does CRA solve?

Create React App is designed to solve the problem of needing to understand a large number of different tools, scripts, configuration utilities, configuration languages, and file types just to get started developing. So now this isn't a problem you need to solve when you're advanced in your project and learning. And it isn't a problem you need to solve when you're an expert and trying to optimize your bundle to minimize what the end user needs to download when they want to use your fancy web application!

Remember, the problem we're talking about here is not one that the experts are solving alone: this problem existed at all skill levels of development and for every person. What's worse, these problems were duplicated every time you started a new project. As developers, we hate duplicating and wasting effort, so the Create React App team set out to remove these speed bumps!

Create React App allows you to get started at any skill level, at any level of comfort and familiarity with JavaScript and its ecosystem. You can start a project and get everything you need, including testing tools and frameworks, with a single command-line tool.

It is not laziness. It is efficiency.

It is not oversimplification. It is removing barriers.

Installing prerequisites for Create React App

First and foremost, you'll need to have npm installed on the computer that you're working on. Without that, there's no way to install the prerequisite libraries and projects. You can download Node and npm for your project at https://nodejs.org, then perform the following steps:

  1. Find the appropriate installer package for your computer and operating system for Node and NPM at https://nodejs.org and follow the instructions provided by the installer.
  2. Install an appropriate code editor or Interactive Development Environment (IDE). I've had the best experiences with Visual Studio Code, so that gets my personal recommendation, but you can use anything you're comfortable with!
  3. Once you've installed Node and npm (if you haven't already), you're ready to go!

Now that everything is set up, working, and installed to the version that we need, we can start iterating! One of the fastest ways to learn a project is to start building it and iterating on it as we learn more, so we're going to do exactly that.

Creating our first Create React App project

You should begin by picking a primary Development directory that you want all of your development work for this book to take place in. Wherever that directory is (I'm always a fan of a Development directory somewhere in my home folder or Documents folder), you'll then create a new project. This will be a throwaway project, since we're going to instead focus on playing around with Create React App and getting comfortable with starting from a blank project. Let's create a new project, which we will call homepage.

For this throwaway project, we'll pretend we're writing a fancy homepage replacement. You can actually pick whatever sort of project you want, but we will be throwing this preliminary project away after this chapter. After you build your project, you should see the following output:

    $ npx create-react-app homepage

Creating a new React app in [directory]/homepage.

Installing packages. This might take a couple of minutes.
Installing react, react-dom, and react-scripts...

[... truncating extra text]

Done in 13.65s.

Success! Created hello-world at [directory]/homepage
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 homepage
yarn start

Happy hacking!

Those instructions that we see after successfully creating a project are critical to our workflow in Create React App. By default, there are four main commands (and a large number of options) bundled into Create React App. Also, if you are using npm instead of Yarn, note that a lot of the comments and output in the Create React App CLI help pages refer to Yarn primarily. Now, these commands (start, build, test, and eject) are relatively self-explanatory, but it is still important to dive a little further and learn a bit more about them.

A quick look at the options of CRA

Before we can dive into building out the app of our dreams with Create React App, we'll have to start by analyzing each of the commands that come with Create React App and what each of them do, plus when to use each command!

Each of the commands corresponds with a specific part of the software development life cycle: building the application, running a development server, running the tests, and deep customization and configuration. Let's explore each of the commands in greater detail!

The yarn start command

The function of this command is to start the development server.

Running start on your Create React App project will bring your project from code to your web browser. That is to say, it will take your project's code and compile everything together. From there, it will load a development server with a default starter template. The other nice thing about this is that it will actually pick up any changes you make to any code (assuming you save that code), so you don't have to constantly play the game of make a change, save the file, restart the server, refresh the browser; instead, you will have instant feedback for any of the changes that you make.

Starting off with a completely fresh Create React App project and running start will yield the following:

The yarn build command

The function of this command is that it bundles the app into static files for production.

Running build takes the application and turns it into something more production-ready. What does that mean? Well, if you're already pretty comfortable with what tools such as webpack and brunch do in terms of turning them into production sites, you basically already know what this accomplishes. If, on the other hand, this all sounds incredibly confusing to you, I'm going to take a little bit of time and explain it in slightly less vague terms.

Essentially, most browsers can't handle code written for Create React App projects just by default. There is a lot of work that needs to be done in taking the code and translating it into something that makes more sense for the browsers, ensuring that it doesn't need to rely on help to interpret everything. From there, the code is also minified! It shrinks things down by renaming functions and variables, removing white space where it can, and doing small optimizations here and there until the code is reduced to a very clean and usable version. Everything is compressed and the file is condensed down as much as it possibly can to reduce the download time (which is important if you're targeting a mobile audience that may not have great internet speed).


Minified means exactly what it sounds like. It is the condensing of code into much smaller values, making it unreadable to humans but highly digestible for computers!

The yarn test command

This function starts the test runner.

Running test does exactly what you'd expect it to do: runs all of your tests for your application. By default, when you spin up a new project with Create React App, your project will include many extra tools that should all be ready for you to start hacking away at the tests. This is especially helpful if you choose to approach a more test-driven development approach to your project, something that can be incredibly useful in a frontend development world.

The first time you run test, you should see some output on your screen that may look a little like this:

     PASS  src/App.test.js
renders without crashing (18ms)

Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 1.976s
Ran all test suites related to changed files.

Watch Usage
› Press a to run all tests.
› Press f to run only failed tests.
› Press p to filter by a filename regex pattern.
› Press t to filter by a test name regex pattern.
› Press q to quit watch mode.
› Press Enter to trigger a test run.

Even better than all of this being built and provided to you is all of the options and additional tools that you get along the way for this! Getting a test framework set up and running consistently in your application can be a major pain in the neck, so having this figured out for you makes your life a thousand times easier. On top of all of this, the test watcher that comes with Create React App projects will also watch and live-reload on changes made to any related files, similar to the start command.

These are just the defaults. It's worth taking a look at some of the extra commands that come along with our test watcher:

  • Press a to run all tests: Like the command says, if you press A in that window, it will just decide to run every single test in your project from zero and output the results. Use this if you need it and need to verify a fully-green test suite at any time.
  • Press f to run only failed tests: I speak from personal experience when I say setting something such as this up in the past was an absolutely dreaded task. This is great when you're taking an approach of red, green, refactor in your project and want only the tests that failed last time and are just trying to get those to pass. You can use this as part of your development methodology to slowly clear away the cruft of your application's failing tests until you're back to all of them passing!

Red, green, refactor: This refers to a common pattern of development where you write your tests first with the intention of them failing, then write the minimum amount of code to make them pass, then refactor the code until they break again, and repeat the cycle. While this is usually used in an interview context instead of real-world development, the process itself is very much a real-world process.
  • Press p to filter by a filename regex pattern: This is a very cool bit of functionality. Let's say you modified some code that affected all functionality related to users, but you have a giant test suite and don't want to test the entire thing. You could instead target all user code by hitting P, and then typing in user and seeing what tests run.
  • Press t to filter by a test name regex pattern: Similar to the previous option, but this goes a step further by looking at what your tests are named (more on this in a later chapter) and runs tests based on those descriptions instead of by the filenames the tests are located in.
  • Press q to quit watch mode: There is not much to explain here; this will quit the test watcher.
  • Press Enter to trigger a test run: Pressing Enter will just redo whatever your last test was, which is very helpful when you're using one of the regex pattern options but don't want to have to retype the pattern every single time.

The yarn eject command

Removes Create React App scripts and preset configurations and copies build dependencies, configuration files, and scripts into the app directory. If you do this, you can't go back to using Create React App on your project!

For this one, it is worth taking a look at what the documentation says for this command. In layman's terms, this turns your project from a Create React App project, turns it into a Webpack configuration, and removes a lot of details of Create React App and the React Scripts project that essentially hides some of the details from you. A similar concept would be buying a computer pre-built versus assembling it yourself (or reassembling it). You may start off wanting everything all put together for you, but maybe some day you'll want to add some more RAM or replace the video card, at which point you'll have to open up what was previously a black box to enable you to configure things further!

This is also something you might do if you need to go outside of the confines of the default project structure and configuration that you get from a base project. This will allow you to turn it back into a standard Webpack project and add new libraries, change the defaults and baseline details, or go even further and swap out other core components.

Let's explore the created project

Finally, we should take a little time to see what precisely gets created and thrown into your project.

Create React App will start off by generating a README for your project called README.md. This is a markdown-formatted file that tells other people how to use your project effectively (or, if you're like me, it reminds you a few months down the line how to use all of the tools and tricks you've implemented in the project down the line).

You will also get a favicon, which is that little icon that shows up next to your website path in the address bar, and is used for any bookmarks to your application down the line. Next, we have the public or index.html file, which is the primary workhorse that includes all of your fancy React code, and more importantly, tells the web browser where to render your React application to; in our case, we have a div element that acts as the main target for React to render to. The source of the file is, by default, as follows:

  <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-
fit=no">
<meta name="theme-color" content="#000000">
<!--
manifest.json provides metadata used when your web app is added to the
homescreen on Android. See
https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json">
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.

Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>React App</title>
</head>
<body>
<noscript>
You need to enable JavaScript to run this app.
</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.

You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.

To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>

I mentioned a div element that acted as the main React render target: the div with an id of root acts as our primary render target and is the critical component to make your application function. Remove this and your application will not render correctly in the browser anymore! Following that, there is the package.json manifest file. This stores all of the dependencies that your project uses, plus some of the metadata used to describe your project (which might include the name, the version, the description, or some other pieces of metadata). We also have a yarn.lock file if you're using Yarn, which locks down the list of libraries and dependencies that your project is using in a way that prevents your project from randomly breaking when one of those libraries updates.

All of your project's dependencies, libraries, and things that make it tick behind the scenes live in the node_modules directory. This also brings us into the src directory, which is arguably the most important directory in our entire project structure! It is where all of the work that we're going to be doing—all of the source code—will live.

Inside of that directory, we have our index.js file, which handles our main render call for React, supported by a package called ReactDOM. This takes in our App.js component, which is our primary root-level component, and tells React where that needs to get rendered to back in that index.html file I showed you earlier.

We also get a little bit of style by default with an index.css file. This is the base-level style sheet that our project will use and we'll be configuring on top of.

In terms of our non-test code, App.js is the final component that we get through Create React App by default. What is in there is not particularly important to us, because we're just going to remove all of the code in that file and start over anyways! App.css stores the style sheet for that component, which allows us to make sure that any style included for each component can be stored and configured independently of each other. We're also given the React logo in the form of a Scalable Vector Graphics (SVG) file, which is the React logo (logo.svg). We don't need that, so feel free to delete it!

serverWorker.js is a file that tells our app how to exist/function as a service worker for a Progressive Web App, but we'll dive into this in a later chapter where we focus specifically on progressive web applications!

Finally, we have the only pre-built test for us. The App.test.js file contains the suite (not a suite, I suppose, since it's only one test, but it will become a suite over time) of tests just for our App.js component. That's it! That's the default project structure for our Create React App project!

Adding code to our project

One of the easiest ways to understand the default project structure is to actually get in there and start messing around with things, so let's do precisely that! We'll delete some of the default code that comes with our project and start building things up ourselves to get a good feel for how the project should be structured and learn how each file interacts for when we start playing around and changing the file structure!

Creating our first component

To create our first component, follow these steps:

  1. Open up the newly-created project in your favorite text editor, and run the start command in that project as well to bring up the browser window to see the results of any changes we make along the way.
  2. Let's do something all developers love to do: delete old code!
  3. Once in the code, we can work through the main primary ways to work with React in the latest JavaScript syntax changes that are included in Babel. Given that, let's take a look at the ways to work with React classes. We can either use functions, or we can use classes to introduce React code to our code base. We'll start off with just using functions and over time incorporate classes as well, and we'll discuss how, when, and why to choose each along the way. Granted, either creation method requires React regardless of the implementation method, so we need to actually import it at the start of our code.

  1. At the very top of the App.js file, we're going to add our import statement:
import React from 'react';

This line tells JavaScript that we want to import the React library, and that we can find the React class from the react npm library (Create React App obviously already included that for us). This gives our code the React support that we need, plus it adds support for JSX templates, and everything else we need to be able to write base-level JavaScript !

  1. With our imports out of the way, let's write up our first bit of code:
const App = () => {
return <div className="App">Homepage!</div>;
};

Here, we're diving a little further into some new JavaScript syntax that you may not be used to if you're coming from the older JavaScript world. The previous line is responsible for creating something called a constant function, which limits our ability to redefine or modify the App function after the fact. This function that we're writing doesn't take any arguments and always returns the same thing. This is a functional component, so we need to write the return statement to return out a JSX template that tells React how to render our React component to the browser. We also make sure to tell React that our main component should have a CSS class name called App.

The className, not class! Class is a reserved keyword in JavaScript , so that's why React needs this one little gotcha!
  1. At the end of this code, we'll need to add an export statement to enable other files (such as our index.js file, specifically) to be able to import the right modules into our code base:
export default App;

Our end result is that when our browser refreshes, we should see Homepage! pop up on the screen!

Wait, what is JSX?

You may not know what JSX is, but if you do, feel free to skip this. Otherwise, I'm going to provide a very quick summary for you!

To put it simply, JSX is just a mixture of JavaScript and HTML that functions essentially as a templating language. This is a bit of a simplified explanation; JSX is actually some smart syntax wrappers around calls to React.createElement, but put together in a way that more closely resembles HTML. This way, we can write interface code that is incredibly similar to HTML, which allows developers, designers, and others to work with our code (assuming they're already comfortable working with HTML), but we also get access to a few extra features since it is a JavaScript -based templating language.

The first bit of functionality that we get is that we can actually embed any JavaScript statements inside of any JSX by wrapping it in curly brackets! A gotcha to this, though, is that we need to remember that JSX is JavaScript first, and as a result there are some words and syntax here and there are are reserved (class being the prime example of this), so there are specific variations you'll need to use when writing JSX (such as className).

Embedding style sheets in our component

Working with React and creating these nice browser-based interfaces is great, but without any kind of styling in place, the whole thing is going to look pretty plain overall. The good news is that Create React App also provides you a nice framework for cleaning up your interfaces as well! Right now, since we deleted a bunch of code, we currently should have an entirely blank App.css file. We'll need to head back to the App.js file and add the following line to the top to make sure it includes our new App component style sheet:

import "./App.css";

This will tell React to make sure the App style sheet is included as part of our component's style sheet. If App.css remains empty, though, that won't amount to much, so let's also change our default style sheet to something a little more interesting:

 .App {
border: 1px solid black;
text-align: center;
background: #d5d5f5;
color: black;
margin: 20px;
padding: 20px;
}

Save the file, head back to your browser window, and you should see something similar to the following:

Okay, we have some code that functions now, and that's a good place to start in our application, so we'll hop over to index.js and quickly figure out precisely how the component gets into the browser. Open up src/index.js:

    import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';

ReactDOM.render(<App />, document.getElementById('root'));

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: http://bit.ly/CRA-PWA
serviceWorker.unregister();

At this point, we've seen import React already. The previous line imports ReactDOM (which houses the main render() function) that we need to be able tell React what component to render, and where to render it to! This comes out of the separate react-dom npm module.

After that, we have another style sheet included, this time being index.css. This will function as our global, baseline CSS file. After that, we import our App component (remember our export statement that we wrote earlier?) with import App from './App'. Note that we can leave the .js off completely, and that we include a dot and a slash in front of the name of the file; this tells Node that we're importing something from our local file system and not from an NPM module instead! App.js lives as a local file inside of our src directory, so the local include suffices.

We end with a new line, import registerServiceWorker from ./registerServiceWorker, which allows us access to implementing service workers for progressive web apps in our Create React App. Progressive web applications are a bit outside of the scope of this tutorial series.

render() is a function call that takes two simple arguments:

  • Which component to render
  • Where to render that component

Since our component name was imported as App, and because we're using JSX, we can treat App like an HTML tag:

<App />

Remember, all tags in JSX need to be closed, whether via shorthand syntax such as in the preceding example or longer syntax such as following:

<App></App>

The final piece to our rendering puzzle is that we need to figure out where in the DOM the React component is that we need to render to, through the document.getElementById('root') line. This tells JavaScript that it needs to find an element on the page with an id of root, which will end up being our rendering target!

There we are! We have an admittedly basic, yet still a full start, application in React that we wrote in almost no time at all, and we had no stress or headaches trying to set up our development server, figure out which libraries we needed, make the code and browser window auto-reload, or, well, you get the idea.

Seriously, what more can a developer ask for?

Looking forward – what will we do?

What more can we ask for? Well, a lot, actually! In the next chapters, we'll go more into depth as we get comfortable with the development workflows afforded to us through Create React App. Let's explore the plan for this project that we're going to be building (since the hello-world application was just an opportunity for us to play around with things and won't be our final project going forward).

The project plan

Over the course of this book, we will build an application entirely using Create React App, encompassing a number of common modern React development techniques, methods, and best practices. We will spend time exploring the different libraries that are available and how to best utilize them in our Create React App project and with minimal effort too! We'll build a project that will take advantage of the very best of modern JavaScript development, taking advantage of the latest features of Babel and React. We'll use the most recent syntax changes in JavaScript to their full effect! We will make sure our application is fully tested and bulletproof, keep it beautiful with CSS modules and Syntactically Awesome Style Sheets (SASS), and even simulate the backend server so that we won't even need a separate backend server just to do development!

Finally, we'll explore how to make our application work online or offline through service workers, and then top off our application by getting it production-ready, and making our application minimized, clean, and deployable!

 

Summary

In this chapter, we explored the options that are made available to us when we're starting up a Create React App project. We also spent a good amount of time exploring the history of frontend development before Create React App, and even got a little bit of time to sit and put together a nice little starter application as an exercise in exploring the default project structure.

You should now feel much more comfortable with Create React App, the default project structure, and the language constructs that will enable us to get more work done in the later chapters, so without any further ado, let's charge ahead and start building a more complex application, which will serve as the basis for each chapter for the rest of our project.

About the Author
  • Brandon Richey

    Brandon Richey is a software engineer and a React enthusiast who has written several popular React tutorials. He has been making professional and hobby programming projects spanning healthcare, personal sites, recruiting, and game development for nearly 20 years! Brandon is the author of the Packt book 'Create React App 2 Quick Start Guide'.

    Browse publications by this author
Latest Reviews (1 reviews total)
great resource to help in learning React
Create React App 2 Quick Start Guide
Unlock this book and the full library FREE for 7 days
Start now