How to think in React: a small introduction

Erin
My Own Utopia
Published in
6 min readOct 16, 2019

In my coding journey I’ve found that the process of learning a new framework or library looks might look something like this:

  1. Stare at 40,000 word+ documentation blankly.
  2. Try to dip my toes in with one aspect of it
  3. Be bitten by some gotcha prompted by a still-unknown and unseen hinge from another aspect of the framework in question

When learning the actual language (e.g. ruby, javascript) the tiny pieces that you learn build up naturally. It feels like placing one brick of knowledge on top of another brick of knowledge, until you have magically built a brick house of all the things you know.

One little piece builds up to the next

Frameworks and libraries end up abstracting a way a lot of their logic from site, with in-built methods that tend to rely on each other, so learning them can feel a bit more like trying to keep track of all the different moving parts— very overwhelming for any newcomer!

Let’s learn a framework

Because React felt like it had so many different things to keep track of, I thought that it would be helpful for at least my own learning (and hopefully others as well) to try to explain some of the foundations of React as simply as possible, through an app I tried to build from start to finish. What did I learn? Well, you’ll have to read through to the end for that…

Start with a plan

It’s so much easier to keep on track if you visualise what the end product needs to look like. React especially benefits from having a diagram in place of what needs to be built.

Our app will:

  1. Get some dogs from an API
  2. Display two small dog photos
  3. When clicked, make the dog photo larger
  4. Like the dog
  5. See our favourite dogs

You can think of planning a React app as a little bit like making a family tree. React documentation has an article about how we think about apps in order to get them set up properly. Although the example shows a grid, as we’ll want to separate concerns on the page by their functionality, we also need to think of how this functionality and information moves from the most “over-seeing” tree trunk of our app to the its smallest branches.

All these branches and leaves from a mighty tree

Thankfully, with React you do have the option to be flexible — you can add more components as you go along should you choose, take them away, or move pieces from one component to the next.

Obviously, this is best avoided. It takes time to go through and re-test all the functionality to make sure that it works as you expect it to, but know that in the beginning, when learning React, if you want to start off with a few small toy apps, you don’t have to throw them out completely and start from scratch if you make a mistake.

#BobRossVibes

npx create-react-app my-app

Let’s start with the easy bit. This is the line you need to get started building a React app. Replace my-app with what you want the app to be called. As I am super creative I have named mine dog-app:

Hit enter and it will do the magic for you.

Once it’s done it’s thing type npm start to open it up in your browser and have a look.

You’re going to get a lot of files, and your folder structure is going to start out looking very long. We want everything to stay tidy, so create a new folder in your main src folder called components.

Components are just JavaScript files, and these can be created as either a JavaScript class (class components), or, if you’re only displaying a small detail, a simple functional (these are cleverly referred to as functional components).

Render our dogs list

I’m always anxious to begin fetching data back from the API and seeing how the information is structured, so I normally begin here.

As this is only a simple app, we’re going to be sticking with declaring our URL in a const variable at the top of one of our components. I’m using the Dog.Ceo API. It’s free, open-source, and incredibly simple — you’ll just receive an image URL.

Writing your code to do a fetch request doesn’t look too different from what you’ve seen before…

get = url => {return fetch(url).then(response=>response.json()).then(dogs=> this.setState({dogs: dogs.message}))}

However, you may have noticed this new addition: setState. And what follows might look even scarier:

componentDidMount() {this.get(URL)}

What are these? Well, if you’re working with Class Components, you have the option to make it ‘stateful’. This is an object, called state, with the key-value pairs to hold the state of that component. We can continue to refer to, and update, what is held in state without needing to continue to make calls to the backend of our app, to make it much faster for user interaction.

Since we’ll want to work with the return value of our API fetch request throughout our app, we’re going to store that in an array within the state object.

state= {
dogs: []
}

Pass some props

As the beauty of React is working with multiple, reusable components, we’ll need to connect these somehow and get the information we set in state to the different parts of our app.

Since step two is display two small dog images after we got our data back from the API (now set in state), let’s make a second component that will just handle showing these dog photos.

We’ll need to tell our component that we need to import React so it understands the React-specific methods we’ll use. At the top of your second, DogList.js file:

import React from 'react';

And declare your class:

class DogList extends React.Component { //...

Class components will utilise a method called render to return the jsx we’ll show on the page. It will look something like this:

render() {  return(
{this.props.dogs.map(dog=> <DogTile key={dog} dog={dog} maximiseDog={()=>props.maximiseDog(dog)} />)}
}export default DogList

You may have noticed that the above is actually rendering a third component — called DogTile, that will display the images. However, let’s look at the first part. DogList received this.props.dogs — an array, that we are mapping over. As we’re within a JavaScript class, we have to specify this — it’s this set of props we’re working with. Props are the React properties that have been passed from one component down the tree to its outer branch.

Going back up one level to our top App component, we passed the initial dog array down from state, via its own render method:

render() {  return (  <div className="App"><DogList dogs={this.state.dogs} </div>)}

App was also a class component — hence the use of this. You’ve created an object called dogs, and assigned it to this object calledstate.dogs. So when you wrote, in DogList, this.props.dogs— you were accessing that variable dogs that was initially assigned in the parent App. The link has been made!

Yes, it is this satisfying

And now… what?

Cast your mind back to the start of this blog when I said that React benefits from having a plan, however, it’s also flexible enough to handle changes. What I’ve learned from setting out to write a simple ‘how-to, start to finish’ blog post ended up being a deep-dive into the nuances of what happens when you try to build things on your own. So, the takeaway :

Experiment. A lot.

Throughout building the app I realised that what I had initially planned for (whether it made sense to render it as a class component or a functional, if I needed to keep track of state or not) might not have made sense once I started to build it out. I was getting a feel for Thinking in React.

There’s certainly still more to finish in regards to styling. But it’s also simple enough to return to for refactoring. How can the code be written even simpler? What additional functionality would make sense to include? And, if you were going to make a simple React app, what would you want to build?

Thanks for reading!

If you liked this, please clap or leave a comment with feedback. Subscribe to my channel for writing on code, design, and lifelong learning.

--

--