A Committed Intro Guide to ReactJS

Hi there! Let’s make a team. We’ll raise hell, and we’ll build a small to-do app together using ReactJS. I got me a good feeling about this!

This 3-part blog series is accompanied by a follow-along Github repository with commit history to match the steps taken below. Feel free to refer to it at anytime along your journey. :)

This intro guide should be perfect if you’re dipping your toes into React, or shall you be keen to embark on a journey to become a full-fledged React developer. For now, I’m only assuming you have Node installed on your machine, and you have some basic knowledge of Git, HTML and JS. We’ll learn as we go, and I’ll have lots of helpful links along the way.

In part 1, we’ll bootstrap an app from scratch and get acquainted with the React component. Ready?

Let’s make a todo list for our todo app

Wait, What Are We Making?

A small todo app we said. Let’s define some requirements first and foremost as the good citizens we are. What will the app do? I suggest we start with the following basic, yet, critical features:

Requirements:
1) display a loading text (while “fetching” todos )
2) load and display todos
3) add new todos
4) toggle todos done/undone
5) delete todos

It’s a good base of features. For now, we won’t worry about styles (CSS) much at all, but focus on JS and React. We’ll have no dependencies (no redux or mobx). React is really quite powerful on its own, and more fun to learn that way as well.

Let’s Ramp Up!

Yup! Let’s set up so we can delve into code rapidly. It used to be a drag to wire up a React project, compile it, and bundle it for the web; but fret not dear friend, it’s now become a rather trivial matter. We’ll use create-react-app to bootstrap withno build configurations”.

Open your terminal, and install cra globally on your machine with this command:

> npm install create-react-app -g

We can now create a React project (all ready to go with babel, webpack and eslint) by typing in this command:

> create-react-app react-todo-app
(“react-todo-app”, or whatever you want to name the app, of course)

Some packages will be installed for you right there and then, and you will be presented with this friendly greeting:

Thanks create-react-app!

In fact, we’ll do exactly as they suggest:

> cd react-todo-app to go into the newly-created directory
> npm start to run the project in dev mode

Now you should see a shining new React app running in your browser. Just like that! (And it’s just as easy to bundle it up for production).

All systems ready-to-launch

At this point, we won’t touch anything. We’ll just initialize a repository with git init, and stage all the files in the directory for our initial commit, and start feeling good, oh yeah.

(If you’re getting into GIT and don’t feel so great using the command line, I’d recommend GitUp as a GUI).

A First Look at a React Component

We’ll do most, if not all, of our work in the src/App.js file. Open up the project in your favorite code editor (VSCode and Atom are popular choices) and let’s take a closer look at this aforementioned App.js:

Holy Moly, a React component!

We are introduced to the mighty React component! I’d venture to say it’s pretty straight forward even to the untrained eye: we have a class on line 5 with a render method that returns some JSX… which seemingly translates to the HTML that we just saw rendered in the browser.

There are lots of className too which is for the CSS to hook into, but we’ll be removing that. There is no dynamic data in there so far, so it’s cool, but really, no magic is happening (if you don’t dwell too long on having HTML-looking bits in your JS file, that is :).

If you’re inclined, try changing the static data “Welcome to React’ on line 11 to something else, and you shall see that change reflected in the browser immediately. You got to love a quick feedback loop!

‘Nuff said about this, let’s clean up this cra intro stuff that we don’t need. We’ll quickly yank that big header, update the title in index.html, remove the react logo, and commit our changes, voila:

(Another dev tip if you’re not already using it: Prettier. It formats code for you. It’s been a game-changer for me. Gone are the days of lining up paragraphs, tabs etc just right, over and over, in the code editor).

Space-Out Styles

We’ll set the most basic styles where we’re merely spacing out everything with a margin on all elements * { margin: 5px 5px 5px 0px; }. We’ll have some decent whitespace between elements, and we don’t have to think much about styles again until we have our functionality up and going (and our designs are ready!). Let’s commit:

Mock Database

One final bootstrap step: we’ll add a mock database to the project. I prepped this file so it should be easy to replace with a Firebase Firestore later, and we can dev without an internet connection meanwhile.

A little mock database is nice in that we remain flexible in the choice of a backend solution later and we can dive straight into UI fun. The downside is that we won’t have persistent data for now, which is fine by me at this very early stage. Perhaps we can add persistence in another blog series:)

I’ll just point out that our little mockDB fakes a 500ms delay in fetching existing todos to simulate the latency of a real-world situation. It’s preloading a couple of todos that we’ll need to display when we load the app. Let’s commit this ‘behind-the-scene” file, and next up, we can get into the the thick of it!

The Time is Upon Us

Now we are ready to get hands-on with React! After we cleaned up cra boilerplate, our src/App.js is left looking like this:

Our blank canvas

What State Are We In?

So what do we do? Ok, let us think about our app, and what sort of state it can be in. What’s our first requirement?

  • display a loading indicator (while “fetching” todos)

So the page should have a ‘loading…’ text indicator until we have something to show; that is, until some todos are fetched and loaded. Clearly, the app can be in two states: “not loaded” (we’re fetching the data) or “loaded” (we got the data–or perhaps even empty data).

Let’s go with this, and simply add a loaded state right on our component . I’m not picking the name state randomly, it is special in a React class. We’ll be using a class field, a concise syntax made available to us via cra and babel compilation (alternatively, we could achieve the same in the class constructor without babel).

We’ll also pepper in an if statement in the render method, so that we return a “loading…” text when the loaded state is false, which it is by default, and always will be at this point. Take a look:

Managing state quickly becomes essential in React

Are you feeling this? To be sure, our app is quite a snoozer at this point since it’s stuck in this loaded: false state forever, but here it is nonetheless in the browser in its full glory:

We need to move on from this state of affairs

Let’s commit this tiny change, because we’re going to experiment a little bit next.

setState (and re-render)

Clearly, we need update the initial state that we just described. How do we enact such wizardry? In React, we use this.setState in the component. (I guess it’s not so much wizardry after all).

Let’s write a first demo action (that’s what we’ll call our functions that trigger a state change). Also, let’s have a <button> in our render method so we can trigger this action ourselves and test it. How about it?

this.setState triggers a new render

Awesome! We created setLoaded() method on line 8 and then we’re attaching it to a button on line 18. setState is our friend. We pass it the state updates we wish to make, and it triggers a new render for us with the updated state. We don’t have to deal with DOM changes by hand. That’s React in a nutshell.

We can also review how we set the click handler in the JSX. Notice it’s onClick and not onclick like you would have in HTML. There’s a few gotchas like that with JSX (it’s className and not class). Another thing here is that you might be tempted to write onClick = {this.setLoaded} but this will break because you’re not binding this (see arrow function vs bind).

Alright-y then… so we’re actually going to scrap this last step, I just wanted to show you setState but the action we cooked up setLoaded doesn’t make too much sense on its own, nor does that button in the loading view. You can git stash and get back to this situation here:

Let’s pick this up in part 2!

This is a perfect time for a short break, and a recent tweet explaining the job of React from Dan Abramov, who’s on the React team at Facebook.

Definitely follow Dan to keep up with React!

In part 2 of this blog series, We’ll forge ahead with building features

[update] : Part 2 is now available

If you can’t quite quench your thirst meanwhile, here are a couple of nice online tools to doodle (or more) with React: 
http://react.jsbin.com/ 
https://codesandbox.io/

I’m on Github and you can also follow me on Twitter. 
Thanks so much for reading!


Photo credits:
-
“A person making a checklist in a notebook” by Glenn Carstens-Peters