A Conceptual Introduction to React Components


11 minute read


I’ve had the pleasure to work on a book about React — React in Action — for Manning this year. It’s been a lot of fun and I’m so excited that it’s starting to be publicly available now through the MEAP program! You can download the first chapter for FREE here. For a short while, you’ll be able to use the discount code mlthomas to get 50% off the MEAP! In this post, we’ll get introduce components in React. If want to learn more about React, check out React in Action!

Components are the foundation of a React application. They’re what the application is made from and are the fundamental unit in React. We’ll teach how to create components in this article! Before we can start we’ll need to figure out what to build and do some careful thinking and planning.

React in Action by Mark T. Thomas | Manning Publications
***Figure 2.1** The anatomy of a React component.*

Imagine an ideal start to a project you’re working on: for one reason or another, the engineering team you’re on has been tasked with creating a simple interface for a social network. This application will be a “next-generation” comment-box, capable of accepting user comments on posts in our main social network product. The interface will serve a crucial role in growing our fictional company, Letters. The business development team are calling it the “Uber for comments”, whatever that means.

A confused-but-determined product manager has worked with the design and user-experience teams to come up with specifications and mockups. For once, there are no other major projects going on (imagine that?). The engineering manager has even begged you “Please try out React, I hear it’s the next big thing and it’s really popular on Hacker News.”

Many frontend development projects begin with a mockup and a description of how the application should work. Your application will also probably interact with some sort of API if it deals with any dynamic or external data. These two things — an API and static mockup — are enough for you to get started on your comment box. See figure 2.2 for what you’ll be building.

React in Action by Mark T. Thomas | Manning Publications
**Figure 2.2** *Comment Box Mockup. This is the static mockup we’ve received from the creative team.*

How do you get started building this? Components seem to play a big role in React, so let’s start with components. To build our applications, we’re going to need to understand and build them, though. How do you know what to turn into a component? We could dive in and start trying to creating components, but without knowing how they work or what purpose they’d serve, we’d end up creating something messy. Let’s do some planning and thinking first.

Thinking with Components

Determining what should be a component involves the same principle used when determining how to organize data and functionality in software in general — the single responsibility principle. This is one of the more straightforward principles in software engineering, and it might come to you intuitively. It states that each class (or component, in our case) should have a single responsibility; each component should, ideally, do only one thing.

What might this look like in real life? Let’s say that there is a module in a program that displays the name of our company, Letters, and makes each of the letters a different color. We’ll call this imaginary module the “Logo module”. How could we use the principle of single-responsibility to improve this module?

By applying the single-responsibility principle, we can ask what reasons there are for the module to change. At this point, it has only two functions, and there are only two important things that could change. Either the name of the company (the textual content produced by the logo module) or the aesthetic of the logo (the colors of the letters) might change. Each of these possible ways to change are their own responsibility, and so the module should be broken into two further modules — “Logo Text” and “Logo Colors”. See figure 2.3 for a visual depiction of decomposing the Logo module.

**Figure 2.3** *One way of breaking up the Logo module from our interface mockup based on different concerns.*

This principle will get you started in dividing up interface elements into components, but it’s also useful for programing in general. When you apply it well, you’ll usually get some substantial benefits, including:

  • Understandability: Code that’s difficult to read, see the flow of, and/or add to, will make adding functionality, refactoring, and debugging significantly harder.
  • Maintainability: Code which is easily reasoned about will generally last longer and produce less errors than fragile code that needsconstant updates and attention.
  • Testability: Highly coupled code will be difficult to isolate and test.

Clean components (and code in general) will be easier to test, think about, and use over the lifetime of an application.

The first step to creating clean code is the initial effort put into planning. You might be tempted to skip this step — “let me get to the code!” — but taking time to think through component relationships in an application that uses React is a prerequisite to using React a pleasure to work with.

Exercise 2.1 Before moving on, take some time to re-visit an exercise from the last chapter. You looked at a web interface and took some time to break it down on your own. Take a minute to revisit the same interface you broke down before and see if you’d do anything differently now that you know a little more about components in React. Would you group things together differently? The same marked-up Github profile interface from chapter 1 is included to jog your memory.

Understanding the application data

Besides the mockup, we need something else before we can organize our components. We need to know what information the API will provide to our application. Based on the mockup, you can probably guess some of the data that we might be getting back.

APIs: What are they?

You might have heard “API” used frequently in engineering and developer circles. What is an API? An API, or, application programming interface, is a set of routines and protocols for building software. If that sounds overly vague, don’t be surprised. An API is a pretty broad term, applying to everything from company platforms to open-source libraries.

In web development and engineering, the term “API” has become almost synonymous with a remote, web-based public API. This means that an “API” is usually a way of exposing defined ways to interact with a program or platform, usually over the internet, and for people to use and consume. Many examples exist, but some of the more familiar ones would be the Facebook or Stripe APIs. They provide a set of methods to interact with their programs and data over the web.

The backend infrastructure team at Letters, our fictional company, has created such an API for us to use. Numerous different forms and types of web-based APIs are out there, but the one that we’ll work with in this book is that of a RESTful JSON API. This means that a server will give us data in the JSON format and the available data organized around resources like “users”, “posts”, “comments”, and so on. RESTful JSON APIs are by far the most common variation of remote API, and this likely won’t be the only time you work with one, if you haven’t already.

Listing 2.1 shows an example of data we’ll receive from the API for our comment box.Try to see how it might match up to our mockup.

Listing 2.1 Sample JSON API

{
    "id": 123, //#A
    "content": "What we hope ever to do with ease, we must first learn to do with diligence. — Samuel Johnson",
    "user": "Mark Thomas",
    "comments": [
        {
            //#B
            "id": 0, //#C
            "user": "David",
            "content": "such. win."
        },
        {
            "id": 1,
            "user": "Peter",
            "content": "Who was Samuel Johnson?"
        },
        {
            "id": 2,
            "user": "Mitchell",
            "content": "@Peter get off Letters and do your homework!"
        },
        {
            "id": 3,
            "user": "Peter",
            "content": "@mitchell ok dad :P"
        }
    ]
}

The API returns a JSON-formatted response containing a single post. It has some important properties, including: id, content, author, and comments. id is a number, content and author are strings, and comments is an array of objects. Each comment has its own id, a user who made the comment, and the actual content.

Multiple Components: composition & parent-child relationships

We’ve the needed data and a mockup, but how do we go about forming components to use that data? We need to know how components can be organized with other components. Like the DOM and virtual DOM that we looked at before, React components are organized into tree structures. Like DOM elements, React components can be nested, which means they contain other components. They can also appear “next to” other components, which means they occur at the same level as other components (see figure 2.4).

That brings up an important question: what sort of relationships can components form? You might think there’d be quite a few different types of relationships that can be created using components. In one sense, you’d be right. Components can be used in incredibly flexible ways. Because they’re self-contained and don’t carry around any “baggage”, they’re said to be composable.

Composable components are easily moved around and can be re-used to create other components. You can think of them almost like Lego bricks. Each Lego brick is self-contained, and can be easily moved around — you don’t have to bring a whole set with the one brick —  and it easily fits in with other components.

Components are composable, which means they can be used almost anywhere you like within your application, but they also form specific relationships: parent and child. If a component contains another component, it’s said to be the parent. A component within another component is said to be a child. Components that exist at the same level don’t share any sort of direct relationship, even though they might be right next to each other. They only “care” about their parents.

Figure 2.4 shows some of the different ways components can relate to each other and be composed together to create new components. Notice the lack of direct relationship between the two child components, although a direct parent-child relationship exists.

![React in Action by Mark T. Thomas | Manning Publications](/static/images/2.5.png)
**Figure 2.4** *Components can form different types of relationships (parent and child), be used to create other components, or even stand alone. They can be easily moved around because they are self-contained and don’t carry any “baggage” when moved. As such, they’re said to be composable.*

Components also form another sort of relationship specific to React: owner and ownee. It’s important to note that the owner-ownee relationship is specific to React, whereas the parent-child relationship is the one you know from the DOM.

Establishing component relationships

We’ve a sense of the data and visual appearance of our interface, as well as what sorts of relationships components can form. Now you can get started on defining your component relationships. This is the process of applying what you’ve learned. You’ll be establishing what is a component and where it’ll go. This process of establishing component relationships won’t look the same for every team or every project. Component relationships are also likely to change over time. Don’t expect perfection on your first time around.

Take a minute or two to try breaking down the components yourself before we move on. You’ve done this a couple times now, but practicing thinking with components will only make working with React easier. As you practice, remember:

  • To keep the principle of single responsibility in mind; components should be organized around single functionality.
  • If you see an interface element repeated many times, that’s usually a good candidate for becoming a component.
  • You won’t get everything perfect the first time, and that’s OK. It’s normal and even good to iteratively improve your code. The initial planning isn’t meant to eliminate future change, but to set the proper initial direction.

With these guidelines in mind, we can look at the available data and mockup and start by breaking things up into a few components. See figure 2.5 for a way to break-up our interface into components.

Figure 2.5 We can break our interface up into a few components. Note that we don’t necessarily need to create components for every single element of the interface, although it might make sense to decompose more parts into components as an application grows. Also note that the same comment component is used for each of the comments attached to a post.

React allows you to be flexible in designing your application. We’ve come up with four components, but there are many different ways that you can go about dividing things up. In larger applications, even something small on the screen — a button, perhaps — could require significant internal logic, making it a good component candidate.

Want more?

Want more? You don’t have to wait for React in Action to be finished to start reading. You can head here to get the MEAP. Use offer code mlthomas to get 50% (that’s right!) off the MEAP! I’m looking forward to getting your thoughts and feedback in the online MEAP forum for React in Action!

React in Action by Mark T. Thomas | Manning Publications

Related: