Getting Started
React is an open-source project created by Facebook. It offers a novel approach towards building user interfaces in JavaScript. Since its initial public release, the library has experienced a fast adoption rate and has created a vibrant community around it.
Over the course of the book, you will learn everything you need to know to get the benefits of React in your projects. since React is only concerned about rendering the UI and makes no assumptions about the rest of your technology stack, this book will you walk through the routing and application architectures that fit in the library’s patterns.
In this chapter, we will go through a few topics at a high level so you can start building applications as quickly as possible. The topics we’ll cover include the following:
Before You Get Started
React fits in the modern JavaScript development ecosystem. To code along with the examples in this book, you will need to have Node.js and npm installed. You should also be familiar with functional JavaScript paradigms as well as some of the language’s newest features, such as arrow functions and classes.
Node.js and npm
JavaScript was born to run on the browser, but Node.js makes it possible to run JavaScript programs on your local computer and on a server through its open source command line tool. Together with npm (Node Package Manager), Node.js has become invaluable for local development of JavaScript-heavy applications, allowing a developer to create scripts for running tasks (such as copying and moving files or starting a local development server, for example) and to automatically download dependencies.
If you don’t have Node.js installed, take your time to install it now by downloading the installer for Windows, Mac or Linux at https://nodejs.org/.
JavaScript ES6
JavaScript is a live language that has been evolving over the years. Recently the community agreed on a set of improvements for the language. Some of the most recent browsers have already implemented such features, and the React community makes extensive use of them (arrow functions, classes, and the spread operator, to name a few). React also encourages the use of functional patterns in JavaScript, so it’s important that you’re familiar with how functions and context works in the language and that you understand methods such as map, reduce, and assign. If you are a little hazy on some of these details, online appendixes on these subjects are provided on the Apress website (www.apress.com/) and on the book’s GitHub page (http://pro-react.github.io/).
Defining React
To get a clear understanding of what exactly React is, I like to define it as this:
React is an engine for building composable user interfaces using JavaScript and (optionally) XML.
Let’s break down this statement to analyze each part:
React’s Benefits
There are a lot of JavaScript MVC frameworks out there. So why did Facebook build React and why would you want to use it? In the next three sections, we’ll explore some of its benefits in order to answer this question.
Reactive Rendering is Simple
In the early days of web development, way before the concept of single page applications, for every interaction the user performed on a page (like hitting a button), a whole new page was sent from the server, even if this new page was only a slightly different version of the page the user was on. That made for a terrible experience from the point of view of the user, but for the developer it was very easy to plan what exactly the user would see at a given interaction or a given point.
Single page applications are constantly fetching new data and transforming parts of the DOM as the user interacts. As interfaces grow more complex, it gets more and more complicated to examine the current state of the application and make the necessary punctual changes on the DOM to update it.
One technique used by many JavaScript frameworks (especially before React appeared) to tackle this increasing complexity and keep the interface in sync with state is data binding, but this approach comes with disadvantages in maintainability, scalability, and performance.
Reactive rendering is easier to use than traditional data binding. It lets us write in a declarative way how components should look and behave. And when the data changes, React conceptually renders the whole interface again.
Since its not viable for performance reasons to actually trash and re-render the entire interface every time state data changes, React uses an in-memory, lightweight representation of the DOM called “virtual DOM.”
Manipulating the in-memory representation of the DOM is faster and more efficient than manipulating the real DOM. When the state of the application changes (as the result of an user interaction or data fetching, for example) React quickly compares the current state of the UI with the desired state and computes the minimal set of real DOM mutations to achieve it. This makes React very fast and efficient. React apps can easily run at 60fps, even on mobile devices.
Component-Oriented Development Using Pure JavaScript
In a React application, everything is made of components, which are self-contained, concern-specific building blocks. Developing applications using components allows a “divide and conquer” approach where no particular part needs to be especially complex. They are kept small and because they can be combined, it’s easy to create complex and more feature-rich components made of smaller components.
React components are written in plain JavaScript, instead of template languages or the HTML directives traditionally used for web application UIs. This is for a good reason: templates can be limiting because they dictate the full set of abstractions that you are allowed to use to build your UI. React’s use of a full-featured programming language to render views is a big advantage to the ability to build abstractions.
Additionally, by being self-contained and using a unifying markup with its corresponding view logic, React components lead to a separation of concerns. In the early days of the Web, different languages were created to force a separation of concerns: HTML for content structure, CSS for styling, and JavaScript for behavior. This separation worked very well when it was introduced because the pervading style of web page at the time was a static presentation. But now that interfaces are magnitudes more interactive and complex, display logic and markup have inevitably become tied together; the separation between markup, styling, and JavaScript turned into just a separation of technologies, not a separation of concerns.
React assumes that display logic and markup are highly cohesive; they both show the UI and encourage the separation of concerns by creating discrete, well-encapsulated, and reusable components for each concern.
Flexible Abstraction of the Document Model
React has its own lightweight representation of the UI that abstracts away the underlying document model. The most notable advantage of this approach is that it enables the use of the same principles to render HTML for the Web as well as native iOS and Android views. This abstraction also leads to other interesting points:
Building Your First React App
You now know that components are the building block of React UIs, but what do they look like? How do you create one? At the bare minimum, a React component is simply a JavaScript class with a render method that returns a description of the component’s UI, like so:
class Hello extends React.Component {
render() {
return (
<h1>Hello World</h1>
)
}
}
You probably noticed the HTML tags in the middle of the JavaScript code. As mentioned, React has a syntax extension to JavaScript called JSX that lets us write XML (and consequently HTML) inline with code.
JSX is optional but it has been widely accepted as the standard way of defining UIs in React components because of its declarative syntax, expressiveness, and the fact that it gets converted to plain JavaScript function calls, means that it doesn’t alter the language semantics.
We will get in more detail about JSX in the next chapter, but the important thing to consider now is that React requires a “transformation” step (or transpilation, if you will) where JSX gets transformed into JavaScript.
In the modern JavaScript development ecosystem, there are a lot of tools that can handle this step. Let’s take a moment to discuss how to set up a development workflow for React projects.
Long gone are the days where we could write all JavaScript in a single file, manually download one or two JavaScript libraries, and glue everything together one a page. And while it’s certainly possible to download or even copy and paste the React library as a minified JavaScript file and start running components immediately, transforming JSX at runtime, nobody does this, except for small demos and prototypes.
In even the most basic scenarios, we want a development workflow that allow us to do the following:
With this in mind, the basic project structure for a React project contains the following:
Figure 1-1 shows the mentioned files and folders structure.
Figure 1-1. Minimum React project files and folders structure
Tip You will find an appendix entirely dedicated to setting up a React project using webpack in the online materials for this book. The appendix covers webpack in detail and shows how to set up advanced options such as hot reloading React components. The online appendixes are available at Apress site (www.apress.com) and at this book's GitHub page (pro-react.github.io).
Getting Started Quickly
To keep focus on learning the React library, a React app boilerplate pack is provided with this book. Download it from apress.com or from the direct GitHub page at https://github.com/pro-react/react-app-boilerplate. The boilerplate project comes with all the basic files and configurations needed to start developing immediately. After downloading it, all you have to do is install the dependencies and run the development server to test the project in the browser. To automatically install all the dependencies, open the terminal or command prompt and run npm install. To run the development server, simply type npm start.
You’re ready to go. Feel free to skip the next topic and go straight to building your first React component.
Or, Do It Yourself
If you want to get your hands dirty, you can manually create the basic project structure in five steps. Since the focus of this book is on the React library, we won’t get into many details or look into optional configurations for now, but you can read more about them in the online appendixes or look the source files for the React app boilerplate project. Both can be downloaded from the Apress website (www.apress.com/) or from this book’s GitHub page (http://pro-react.github.io/).
The next key, output, tells webpack where to save the single JavaScript file containing all the modules packed in the correct order.
Finally, in the the module loaders section, you pass all .js files through Babel, the JavaScript compiler that transforms all JSX into plain JavaScript code. Bear in mind that Babel does more than that, though; it allows the usage of modern JavaScript syntax such as arrow functions and classes.
With this set up, the next time you want to run the local development server, simply type npm start.
Creating Your First Component
With a basic project structure in place that manages dependencies, provides a module system, and transforms JSX for you, you can now recreate the Hello World component and render it on the page. You will keep the same code for the component, but add an import statement to make sure the React library gets included in the bundled JavaScript.
import React from 'react';
class Hello extends React.Component {
render() {
return (
<h1>Hello World</h1>
);
}
}
Next, you will use React.render to display your component on the page, as shown here and in Figure 1-2:
React.render(<Hello />, document.getElementById('root'));
Figure 1-2. Your first component rendered in the browser
Tip While it’s possible to render directly into a document body, it’s usually a good idea to render into a child element (usually a div). Many libraries and even browser extensions attach nodes to the document body, and since React needs to fully manage the DOM tree under its control, this can cause unpredictable issues.
Saving a little typing
A commom technique used by many developers to save a little typing is to use destructuring assignemt in the module import, in order to have direct access to the modules internal functions and classes. In our previous example, we could use it to avoid typing “React.Component”:
import React, { Component } from 'react';
class Hello extends Component {
render() {
return (
<h1>Hello World</h1>
);
}
}
It surely does not have a really big impact in this example, but the cumulative impact in bigger projects justifies its usage.
Note Destructuring assignment is part of the specification for the next version of javascript. This and other future version topics that can already be used in React are covered in the online Appendix C.
Dynamic Values
In JSX, values written between curly braces ({}) are evaluated as a JavaScript expression and rendered in the markup. If you want to render a value from a local variable, for example, you could do this:
import React, { Component } from 'react';
class Hello extends Component {
render() {
var place = "World";
return (
<h1>Hello {place}</h1>
);
}
}
React.render(<Hello />, document.getElementById("root"));
Composing Components
React favors the creation of simple reusable components that are nested and combined to create complex UIs. Now that you’ve seen the basic structure of a React component, let’s make sense of how they can be composed together.
Props
A key factor to make components reusable and composable is the ability to configure them, and React provides properties (or props, in short) for doing so. Props are the mechanism used in React for passing data from parent to child components. They can’t be changed from inside the child component; props are passed and “owned” by the parent.
In JSX, props are provided as tag attributes much like in HTML. As an example, let’s build a simple grocery list composed of two components, the parent GroceryList component and the child GroceryItem component:
import React, { Component } from 'react';
// Parent Component
class GroceryList extends Component {
render() {
return (
<ul>
<ListItem quantity="1" name="Bread" />
<ListItem quantity="6" name="Eggs" />
<ListItem quantity="2" name="Milk" />
</ul>
);
}
}
// Child Component
class ListItem extends Component {
render() {
return (
<li>
{this.props.quantity}× {this.props.name}
</li>
);
}
}
React.render(<GroceryList />,document.getElementById("root"));
Besides using named props, it’s also possible to reference the content between the opening and closing tags using props.children:
import React, { Component } from 'react';
// Parent Component
class GroceryList extends Component {
render() {
return (
<ul>
<ListItem quantity="1">Bread</ListItem>
<ListItem quantity="6">Eggs</ListItem>
<ListItem quantity="2">Milk</ListItem>
</ul>
);
}
}
// Child Component
class ListItem extends Component {
render() {
return (
<li>
{this.props.quantity}× {this.props.children}
</li>
);
}
}
React.render(<GroceryList />, document.getElementById('root'));
Presenting the Kanban Board App
Throughout this book you’re going to build several small components and sample code for each topic. You’re also going to build one complete application, a Kanban-style project management tool.
In a Kanban board, project activities correspond to cards (Figure 1-3). Cards are assembled into lists according to their status and are supposed to progress from one list to the next, mirroring the flow of a feature from idea to implementation.
Figure 1-3. A sample Kanban board
There are many Kanban-style project management apps available online. Trello.com is a prominent example, although your project will be simpler. Your final project will look like Figure 1-4 and the data model the Kanban app will consume is shown in Listing 1-5.
Figure 1-4. The Kanban app you’ll build in the next chapters
Defining Component Hierarchy
The first thing to understand is how to break the interface into nested components. Here are three things to consider.
If you apply these concepts to the Kanban app, you will come to the composition shown in Figure 1-5.
Figure 1-5. The hierarchy of components in the Kanban App
The Importance of Props
Props are of key importance in component composition. They are the mechanism used in React for passing data from parent to child components. Props can’t be changed from inside the component; they are passed and “owned” by the parent.
Building the Components
Having figured out the interface hierarchy, it’s time to build the components. There are two main approaches to building the components: top-down or bottom-up. That is, you can either start with building the components higher up in the hierarchy (such as the App component) or with the ones lower in it (like the CheckList component). To get an insight of all the props being passed down and how they are used in child components, you will start building your Kanban components from top-down.
Additionaly, to keep the project organized and to make it easy to maintain and implement new features, you’re going to keep each component in its own JavaScript file.
App Module (App.js)
You will keep the app.js file really simple for now. It will only contain the data and it will only render a KanbanBoard component. In this first iteration of your Kanban app, the data will be hard-coded on a local variable, but in future chapters you will fetch it from an API. See Listing 1-6.
KanbanBoard Component (KanbanBoard.js)
The KanbanBoard component will receive the data as props and will be responsible for filtering the status to create three list components: “To Do,” “In Progress,” and “Done”. See Listing 1-7.
Note As stated in the beginning of this chapter, React’s components are written in plain JavaScript. They don’t have the loops on branching helpers that you may find on template libraries such as Mustache, for example, but that’s not bad news since you have a full-featured programming language at your fingertips. In the next components, you will use filter and map functions to work with data from the cards array.
The List component will just display the list’s name and render all the card components within it. Notice that you will map the cards array received via props and pass individual information such as the title and description down to the card component, also as props. See Listing 1-8.
Card Component (Card.js)
The Card is the component with which the user will interact most. Each card has a title, a description and a checklist, as shown in Figure 1-6 and Listing 1-9.
Figure 1-6. The Kanban app’s card
Notice the use of the className attribute within the Card component. Since JSX is JavaScript, identifiers such as class are discouraged as XML attribute names, hence the use of className. This subject will be further discussed in the next chapter.
Checklist Component (CheckList.js)
Finally, there is the component that makes the bottom part of the card, the checklist. Notice that you’re still missing the form to create new tasks; you will work on this later. See Listing 1-10.
Finishing Touches
The React components are done. To make things look pretty, now let’s write some CSS to style the interface (see Listing 1-11). Don’t forget to create an HTML file to load the JavaScript and CSS files, and a div for React to render into (an example is shown in Listing 1-12).
If you followed along, you should see something similar to Figure 1-7.
Figure 1-7. The composed components interface
Introducing State
So far you’ve seen that props are received by the component and are immutable. This leads to static components. If you want to add behavior and interactions, a component needs to have mutable data to represent its state. React’s components can have mutable data inside this.state. Note that this.state is private to the component and can be changed by calling this.setState().
Now comes an important aspect of React’s components: when the state is updated, the component triggers the reactive rendering, and the component itself and its children will be re-rendered. As mentioned, this happens very quickly due to React’s use of a virtual DOM.
Kanban App: Togglable Cards
To illustrate state in components, let’s add a new functionality to your Kanban app. You’re going to make the cards toggle. Users will be able to show or hide details about the card.
It’s possible to set a new state at any time, but if you want the component to have an initial state, you can set it on the class constructor. Currently, the Card component doesn’t have a constructor, only a render method. Let’s add a constructor function to define a new key called showDetails in the component’s state (note that the import/export statements and the contents of the render method were omitted for brevity). See Listing 1-13.
In this sequence, you change the JSX in the render method to only render the card’s details if the state property showDetails is true. To make this, you declare a local variable called cardDetails, and only assign actual data if the current state showDetails is true. On the return statement, you simply return the value of this variable (which will be empty if showDetails is false). See Listing 1-14.
To finish, Let’s add a click event handler to change the internal state. Use the JavaScript ! (not) operator to toggle the Boolean property showDetails (if it’s currently true, it will became false and vice-versa), as shown in Listing 1-15.
When running the example on the browser, all contacts will start closed and can be toggled on click (Figure 1-8).
Figure 1-8. Togglable Kanban Cards
Summary
This chapter explored what React is and what benefits it brings to the universe of web development (primarily a very performant, declarative approach to structure your application user interface into components). You also created your first components and witnessed all the basic concepts of React’s components: the render method, JSX, props, and state.