The last major new topic we’re going to look at is less about React and more about setting up your development environment to build a React app. Until now, we’ve been building our React apps by including a few script files:
These script files not only loaded the React libraries, but they also loaded Babel to help our browser do what needs to be done when encountering bizarre things like JSX (Figure 13.1):
The solution is to set up your development environment so that your JSX-to-JS conversion is handled as part of getting your app built (Figure 13.2):
In the following sections, we’re going to look at one way to set up your development environment using a combination of Node, Babel, and webpack. If all of this sounds bizarre to you, don’t worry. We’ll use a really nifty solution created by Facebook that makes all of this a breeze.
A few years ago, getting your build environment set up would have been a huge pain because it involved manually configuring all the tools we’ve talked about. You would have had to ask your really smart friend for some advice. You might even have questioned your decision to learn programming and React in the first place. Fortunately, the Create React project (https://github.com/facebookincubator/create-react-app) came about and greatly simplified the process of setting up your React environment. You just run a few commands on your command line, and your React project is automatically created with all the proper behind-the-scenes configurations.
To get started, first make sure you have the latest version of Node installed (https://nodejs.org/). Then bring up your favorite command line. If you aren’t too familiar with command lines, don’t worry. On Windows, launch either the command prompt or the BASH shell. On Mac, launch the Terminal. You’ll see something that looks like this:
It’s basically some bizarre window with a blinking cursor that allows you to type things into it. The first thing you need to do is install the Create React project. Type the following in your command line and press Enter/Return:
It can take anywhere from a few seconds to a few minutes, but once your installation has completed, it’s time to create our new React project. Navigate to the folder where you want to create your new project—this can be your desktop, a location under Documents, and so on. When you’ve navigated to a folder in your command line, enter the following to create a new project at this location:
You’ll see something that looks as follows:
After the command has fully executed, you’ll have a project called helloworld created for you. Don’t worry too much about everything that’s going on; we’ll look at the project contents later. For now, the first thing to do is test this project. Navigate into the newly created project’s
helloworld folder by typing the following:
From inside this folder, enter the following to test the app:
If you have yarn installed, Create will prefer it over npm for the install and you’ll see onscreen instructions saying to use
yarn start instead of
Your project will get built, a local web server will get started, and you’ll see your project running, similar to the following image:
If everything worked out properly, you should see the same thing. If this is your first time creating a new React project using the command line, congratulations! This is a really big step. You aren’t done, though. Now, we need to take a few steps back and revisit what exactly just happened.
Right now, we just see whatever default content the
create-react-app command generated for us. That isn’t very helpful. First, let’s take a look at what exactly gets generated. Your file and folder structure after running
create-react-app helloworld will look as in Figure 13.3:
index.html in your
public folder gets loaded in your browser. If you take a look at this file, you’ll realize that it’s very basic. Here are the contents of this file with all the comments removed:
The important part to look at is the
div element with an
id value of
root. This is where the contents of our React app ultimately get printed to. Speaking of that, the contents of our React app with all the JSX are contained inside the
src folder. The starting point for our React app is contained in
ReactDOM.render call that looks for the
root element we called out inside
index.html. You’ll also see a bunch of
import statements at the top of the page. These
ReactDOM, are external to your project but still capable of being imported. I can say a lot about module loading, but for your sanity (and mine!), let’s just leave that topic alone for now.
In our code right now, we’re importing both the React and React-DOM libraries. That should be familiar from when we included the script tags for them earlier. We’re also importing a CSS file, a service worker script that we’ll reference as
registerServiceWorker, and a React component that we’ll reference as
App component seems like our next stop, so to see what’s inside it, open
Notice that our
App.js file has
import statements of its own. Some, such as the one for React and Component, seem necessary, given what our code is doing. The last line here is interesting:
export default app. It contains the
export command and the name that our project will use to identify the exported module. You’ll use this exported name when importing the App module in other parts of the project, such as
index.js. Closing out what this file is doing, it also imports an image and CSS file that are needed to make this page work.
You’ve now seen a different way of structuring code using some potentially new keywords. What’s the purpose of all of this? These modules,
import statements, and
export statements are just niceties to make our app’s code more manageable. Instead of having everything defined in one giant file, you can break your code and related assets across multiple files. Depending on which files you reference and what files get loaded ahead of other files, our mysterious build process (currently kicked off with an
npm start) can optimize the final output in a variety of ways that we don’t need to worry about.
The important point to note is that none of these things you are doing to your code affect the functionality of your final app in any major way. Behind the scenes, when we’re ready to test our app, a build step takes place. This build step makes sense of all of the various files and components you are importing, to present them as an easily digestible set of combined files for the browser to take care of. We’ll get one JS file with all the relevant pieces represented:
Now that you’ve gotten a better idea of what this project is doing, let’s modify the example. We want to display the words
Hello, world! to our screen. We’ll go about this by creating a component, appropriately called
HelloWorld, to handle it for us. The new part in this isn’t that you get some text to display onscreen; you’re a pro at that by this point. The part to focus on is how to structure the files in your project to ensure that you’re creating your app the right way.
To get started, go to your
src directory and delete all the files you see there. Then create a new file called
index.js. Inside that file, add the following contents:
We’re importing our React and ReactDOM modules here. We’re also importing a component called
HelloWorld that we are specifying in our
ReactDOM.render call. That component doesn’t exist, so we are going to fix that next.
In the same
src directory that we’re in right now, create a file called
HelloWorld.js. Then go ahead and modify it by adding in the following:
Take a moment to look through what you’ve added. You shouldn’t see anything really exciting going on here—just a boring
import statement, our
HelloWorld component that prints some text to the screen, and (in the last line) code that tags our
HelloWorld component for exporting so that it can be imported by another module, such as our
With these changes made, we can test the application. Make sure you’ve saved all your changes. Go back to the command line and type in
npm start. If your app was already running behind the scenes, you would automatically see it update with the latest changes. If that didn’t happen or your app stopped, press Ctrl+C to stop the session and enter
npm start again.
You should see something similar to this on your screen:
If this is what you see, great! Our example is working now, but it looks a little too plain. Let’s fix that by adding some CSS. Create a stylesheet called
index.css, and add the following style rule into it:
In this approach for building apps, creating the stylesheet is only one part of what you have to do. The other part requires you to reference the newly created
index.css in the
index.js file. Open
index.js and add the highlighted
import statement for it:
If you go back to your browser, you’ll notice that the current setup automatically refreshes your page with all the latest changes. You’ll see the words
Hello, world! centered vertically and horizontally for you. Not bad, but we can do better.
The last thing we want to do is make our text appear in a more stylish fashion. We could add the appropriate style rules to
index.css itself, but the more appropriate solution is to create a new CSS file that we reference only in our
HelloWorld component. The end result of both approaches is identical, but you want to get into the practice of grouping related files (and their dependencies) together, as part of being a better developer.
Create a new file called
HelloWorld.css inside the
src folder. Add the following style rule into it:
All that’s left is to reference this stylesheet in the
HelloWorld.js file, so open that file and add the highlighted
If you go back to your browser, you know that everything worked out fine if you see something like the following:
You’ll see the words
Hello, world! displayed, but with a little more style and pizazz (as the cool kids say these days) than they did a few moments ago.
We’re almost done. We’ve got just one more thing left to do. So far, we’ve been building this app in development mode. In this mode, our code isn’t minified and some of the things run in a slow/verbose setting so that we can debug issues more easily. When it’s time to send the app live to our real users, we want the fastest and most compact solution possible. For that, we can go back to the command line and enter the following (after stopping the build by pressing Ctrl+C):
The script takes a few minutes to create an optimized set of files for you. Once it has run to completion, you’ll see some confirmation text that looks as follows:
When this has completed, you can follow the onscreen prompts to deploy it to your server or just test it locally using the popular
serve node package.
Also take a moment to browse through all the files that were generated. The end result is just plain HTML, CSS, and JS files. No JSX. No multiple JS files. We have just a single JS file that contains all the logic our app needs to work.
So that just happened! In the preceding sections, we used the awesome Create React solution to create our React app in a modern way. If this is your first time building apps like this, you’ll want to get more familiar with this approach. We use the
create-react-app command for future React examples; our earlier in-browser approach was just to help you learn the basics without fiddling with all of what you saw here. Under the covers, Create React hides a lot of the complexity that goes with tweaking Node, Babel, webpack, and other components. That is its greatest strength, as well as its greatest weakness.
If you want to go beyond the happy path that Create React provides, you’ll need to learn a lot of the complexity hidden underneath. Covering all of that goes beyond this book. As a starting point, take a look at what’s specified in the various JS files under the
Note: If you run into any issues, ask!
If you have any questions or your code isn’t running like you expect, don’t hesitate to ask! Post on the forums at https://forum.kirupa.com and get help from some of the friendliest and most knowledgeable people the Internet has ever brought together!