React Dev Environment Prep
Tutorial to prepare your dev environment and bootstrap a new app with create-react-app
This tutorial is designed as a pre-requisite to learning to code with React. It is not intended to teach you the fundamentals of React, but helps you to prepare your environment and create a sandbox that you can use to learn in later on.
👍 This tutorial outlines:
- Downloading the necessary tools to start developing a React app on a Mac
- Introduction of
create-react-appand how it can help you bootstrap a new app quickly - The meta fundamentals of React apps (pun intended), including bootstrapped file structure and essential terminal commands
- A few pro tips to know before you start coding, including project organization, additional dependency recommendations, and the basics of Node modules.
🙅 This tutorial does not:
- Explain fundamental React concepts like components, state, and props
- Dive into the code
- Support operating systems other than MacOS — these instructions will not be helpful for PC or Linux users.
💁 However, I have included links to docs and tutorials that teach all about React concepts and coding with React, which I highly recommend new React developers read after this post.
Dev Environment Prerequisites:
Working on a new or factory reset computer? Here are instructions to set up your dev environment, which includes a few vital tools I used in this tutorial (and general advice on how to make your coding environment work for you).
Download / Update Node and npm
Check if you have them downloaded already by typing the following in your Terminal:
npm --version
node --versionYou should see 2 version numbers printed (one for each line).
- 👍 If you see 2 version numbers, you’re all set!
- 👎 If you see errors and/or don’t see 2 versions numbers, follow these instructions to download correctly. (Hint: There is a Wrong Way to download npm! Check out my link to avoid annoying pitfalls later on).
Once you have confirmed that node and npm are installed correctly, you are ready to get started with React! 🎉
Create a single page React app:
Bootstrap a new React app
I followed the React docs, as well as this tutorial to Create a New React App which outlines quick commands to bootstrap, build, and start a new skeleton frontend project with React.
🏎 TLDR —
Navigate to the directory where your coding projects live (mine is ~/Code), and run the command to bootstrap a new app:
cd ~/Code
npx create-react-app create-react-app-testnpm will install create-react-app, react, react-dom, and react-scripts. It will then create a React project in a new directory, which you named in the bash command (in my case, create-react-app-test).
- 👍 If successful, you should see a lot printed out in your console, including a line that says something like this:
Success! Created create-react-app-test at ~/Code/create-react-app-test- 👎 If you run into any errors, stop 🛑. You’ll need to fix them / successfully create a React app before proceeding.
Push your code up to GitHub
We love to track our work in github! 👾 Conveniently, the create-react-app script initializes a local git repo and makes an initial commit. All you need to do is create a remote repo and push it up. 👏
- Go to your GitHub account in the browser.
- Click the
+button in the top right -> New Repository - Give it the same name as the local repo (not required but for sure the best practice). In my case it was
create-react-app-test. - Do Not initialize with a README — we will be pushing an existing repository.
- Click the
Createbutton. - Copy the script to “push an existing repository from the command line”. Navigate into new directory in your Terminal, then paste the GitHub script and run it.
cd create-react-app-test
git remote add origin <yourGithubRepoUrl>
git branch -M main
git push -u origin main- Refresh the page in GitHub to check that your new React project pushed successfully.
Explore
Time to check out what was Bootstrapped for us! The README of the project is a good place to start. 👀 📖
Terminal Commands
There are a few key Terminal commands to be aware of when you are first getting started:
npm start: This starts the local server. It builds and runs your React app, which can be viewed by navigating in your browser to http://localhost:3000/. Once again, React is super convenient and opens this page in the browser automatically if you grant Terminal that type of permission. Give it a shot and see what create-react-app generated for you! This uses live reload, so as you make changes to the code it will automatically apply in the browser when you save. No need to re-start the server.
npm test or npm run test or npm t: Runs the test files. You can learn more about Jest, the testing framework, in their docs. This command uses a watcher, so the tests will automatically run again every time you make changes and save.
- If you want to dig a little deeper into the Jest config used by
create-react-app, you can view it here (see note at the bottom of this section for further investigations). My oversimplified explanation: This command finds all files ending with*.test.jswithin thesrcdirectory (even if they are nested in sub-directories) and runs them. You can make a customized config if you have advanced needs (probably not a good idea and not necessary for 99% of projects). To do that, you need to configure the script to use yours instead of the one defined increate-react-app. More on that here.
npm install or npm i: installs all your packages specified in package.json into the node_modules directory.
- If you make any changes to
package.json, you’ll need to runnpm ito apply the changes. Note, this is not a React-specific command — it is a global functionality ofnpmand is used by most JS frameworks and projects. - You can view specific details about which versions and sub-dependencies are loaded by viewing
package-lock.json, and can directly look at the code in the generatednode_modulesdirectory. - It is not a good idea to edit
package-lockornode_modulesdirectly. These are generated when you runnpm iornpm updateso that means your changes will be lost. You’ll notice both are listed in.gitignore— generated files and directories do not need to be tracked, because they shouldn’t be modified manually. - If you need to change a package version, you can specify it in
package.jsonand runnpm clean installornpm ci.
npm run build and npm run eject: I won’t get into these today, since they aren’t particularly related to the initial development phase or the fundamentals of React. You can read more about these in your project’s README.
Note: If you want to dig deeper, you can see the basic script definitions in package.json in the scripts section (you can even add your own if you’re a bash wizard). The React scripts are defined in the aptly named react-scripts, which are defined here.
View the code
Time to look into the code 👀. Open up the project with your favorite code editor. I use Visual Studio Code for front-end development.
For newcomers, here is a quick tour:
/srcdirectory holds all javascript (including tests) and css. Everything in this directory can reference everything else, which means you can access them viaimportstatements. If you open up/src/index.jsyou’ll see examples of this at the top of the file./publicdirectory hold the base html (think headers and meta tags) and related resources (like the favicon, manifest, and robots.txt). This is where metadata for the browsers lives. The<body>ofindex.htmlis replaced by the bundled React scripts (in/src) when you build and run./package.jsonis where package imports are specified. This list is what tellsnpmwhich node_modules to download./node_modules— When you build the app, you’ll see this directory appear (in most editors the folder is a different color which indicates it is generated code). This holds all of thepackage.jsonimports. Do not modify these! They will be regenerated whenever you runnpm installornpm clean installornpm update./buildis another generated directory that appears when you build the app. Once again this is not for editing and is listed in the.gitignorefile. This is what contains the compiled app for deployment./src/*.test.jsAny files that end with.test.jsare test files, and will be run when you use thenpm testcommand./src/index.jsis the root file, which set ups the React framework and renders the base component(s). You probably won’t need to edit this too much at least in the beginning phases of development./src/App.jsis the base React component! It is rendered byindex.js. This is where you can get started coding, adding sub-components, and just go crazy.
Make Adjustments
Organize your files
As you start to build your React app, the /src directory will immediately get cluttered and unmanageable if you don’t start to organize into sub-directories. I like to sort first by file types. This is pretty common and can be considered best practice.
Get Anna Bush’s stories in your inbox
Join Medium for free to get updates from this writer.
/src/styles — For all your .scss and .css files.
/src/components — For all your .js component files (not including tests). This would hold App.js, but not index.js since it’s the app root and not technically a Component.
/src/tests — For all the tests.
I highly recommend doing this before you start working, because you need to update all of the import statement file-paths for every file that gets moved. This can be a big headache if you have a lot of files. For example, after moving the bootstrapped files into the directories listed above, the import statements in App.js (now located in /src/components) became this:
import logo from '../logo.svg';
import '../styles/App.css';../syntax tells it to look up one level in the folder structure. In other words, instead of looking in/components, go up a level and look in/srcinstead.- Stylesheets have been moved to
/stylesfolder.
After you’re done with the move, you can check your work with npm start and npm test and ensure both run without errors.
If you have a particularly large project, you might want additional sub-directories in all of these folders. Try to keep the file structure normalized and as close to the website design as possible. For example, if you have several components used on the homepage (pretty common), you might have a file structure like this:
src:
styles:
homepage:
component1.scss
component2.scss
components:
homepage:
component1.js
component2.js
tests:
homepage:
component1.test.js
component2.test.jsNotice, each section has an identically named folder for the page title, homepage, and identically named files for the separate components. This helps keep your files clear and easy to navigate for your teammates or for Future You 🗓 ⏱ 🤓.
Sass
I highly recommend adding Sass to your project. I’m frankly surprised that React doesn’t have this included by default. Sass is like CSS but so much more flexible and powerful.
To add to your React project, use the following command in the Terminal:
npm i sassThis adds Sass as a dependency in package.json and loads it into the project.
If you’re not convinced yet, here are a few of my favorite Sass features:
It allows you to nest style-sheets like this:
.my-page {
.page-header {
background-color: blue;
}
.page-body {
color: purple;
}
}This is compiled and translates to the following vanilla CSS:
.my-page .page-header {
background-color: blue;
}
.my-page .page-body {
color: purple;
}Seems simple right now, but SO useful once you start styling large pages and worrying about the scope of your CSS styles.
You can also add variables!! This is huge!
$site-primary-color: green;.page-header {
background-color: $site-primary-color;
}You can create module files which can be imported in other stylesheets and used by your page-specific files. These are a great place to keep those variables I mentioned. For example, I always create a _colors.scss file to hold color variables. This makes it super easy to change the color scheme of your website later on. Notice that the filename starts with _. This is not required, but it’s suggested as a best practice to keep your files organized.
It can be imported for use in your other scss files with:
@import 'colors';Sass is awesome. You’ll never go back to vanilla CSS. Read more about Sass here in their docs.
Moment.js
Another highly useful library, this one makes parsing, displaying, and manipulating dates in JavaScript infinitely easier than any other time/date library I’ve used in any coding language. If you think you’ll be dealing with dates and/or times at all, you’ll want this import.
The docs are awesome.
Note: It does say that Moment is deprecated — it has said that for years. Yet still I’ve seen it used by all sorts of teams, from start-ups to big corporations. It’s just that good. Nobody wants to let it go. And I’ve never seen any bugs or issues that you might see with other deprecated libraries, so I guess just don’t worry about it. 🤷♀
Install in your project dir with:
npm i momentImport it at the top of any component files where it will be used:
import * as moment from 'moment';Use it inside a function in the code:
function momentPlayground() {
var randomDate = '2016-08-15T14:32:00Z';
var randomDateMoment = moment(randomDate); // converts string to a Moment object
var timeNow = moment(); // creates a new Moment object for the current time
// print dates in ISO with .format()
console.log('givenDate, ', randomDateMoment.format());
// optionally provide the desired string format instead of ISO
console.log('timeNow, ', timeNow.format('MM dd, yyyy, HH:mm a'));
// manipulate
var modifiedDate = randomDateMoment.add(3, 'years');
var diff = timeNow.diff(randomDateMoment); // returns a Duration of time between two Moments
// so much more in the docs.
}Super useful. Highly recommend. 👌
React Bootstrap
Bootstrap makes styling so much easier, and comes with a bunch of pre-styled components out of the box. I’ve used Bootstrap on every single front-end I’ve worked on, whether I created the project or inherited it from others. It’s an essential front-end tool that is available for most (or maybe all) frameworks, including React. Here are the docs.
Import it in the Terminal in your project directory:
npm i react-bootstrap bootstrapIf using sass, add the stylesheets in either index.scss or App.scss, so they’ll be applied to all the app’s descendent components:
$theme-colors: (
"primary": lightblue,
"info": green,
"danger": red
);
@import "~bootstrap/scss/bootstrap";You’ll see before the @import command, I added a few customizations to the color scheme. If you want to make any customizations, they need to happen before the @import statement so they can be applied.
Finally, use the bootstrap components by importing them and using them like any normal components:
import Button from 'react-bootstrap/Button';
...
return (
<Button>Bootstrap Button</Button>
)
...Start Coding
The React docs provide a nice tutorial which gives an overview of the basic React concepts like Components, Props, and State and how to use them. I won’t restate any of that here — the docs are pretty good.
You are on your own from here — happy coding!
Resources
Instructions to set up your dev environment (recommended before diving into this tutorial if you are a new developer or on a new machine).
Instructions to download npm and node (also recommended for devs with new computers).
I created this GitHub repo while writing this tutorial. It includes the changes that I recommended, such as the addition of a few dependencies and file re-organization. Feel free to poke around!







