This book assumes that you already know what React is and what problems it can solve for you. You may have written a small/medium application with React, and you want to improve your skills and answer all of your open questions. You should know that React is maintained by developers at Facebook and hundreds of contributors within the JavaScript community. React is one of the most popular libraries for creating user interfaces, and it is well-known to be fast, thanks to its smart way of touching the Document Object Model (DOM). It comes with JSX, a new syntax to write markup in JavaScript, which requires you to change your mind regarding the separation of concerns. It has many cool features, such as server-side rendering, which gives you the power to write universal applications.
To follow this book, you will need to know how to use the terminal to install and run npm packages in your Node.js environment. All the examples are written in modern JavaScript, which you should be able to read and understand.
In this first chapter, we will go through some basic concepts that are essential to master in order to use React effectively, but are straightforward enough for beginners to figure out:
Reading the React documentation or blog posts about React, you have undoubtedly come across the term declarative. One of the reasons why React is so powerful is because it enforces a declarative programming paradigm.
Consequently, to master React, it is essential to understand what declarative programming means and what the main differences between imperative and declarative programming are. The easiest way to approach the problem is to think about imperative programming as a way of describing how things work, and declarative programming as a way of describing what you want to achieve.
A real-life parallel in the imperative world would be entering a bar for a beer, and giving the following instructions to the bartender:
- Take a glass from the shelf.
- Put the glass in front of the draft.
- Pull down the handle until the glass is full.
- Pass me the glass.
In the declarative world, you would just say: Beer, please.
The declarative approach of asking for a beer assumes that the bartender knows how to serve one, and that is an important aspect of the way declarative programming works.
Let's move into a JavaScript example, writing a simple function that, given an array of uppercase strings, returns an array with the same strings in lowercase:
toLowerCase(['FOO', 'BAR']) // ['foo', 'bar']
An imperative function to solve the problem would be implemented as follows:
const toLowerCase = input => {
const output = [];
for (let i = 0; i < input.length; i++) {
output.push(input[i].toLowerCase());
}
return output;
}; First of all, an empty array to contain the result gets created. Then, the function loops through all the elements of the input array and pushes the lowercase values into the empty array. Finally, the output array gets returned.
A declarative solution would be as follows:
const toLowerCase = input => input.map(value => value.toLowerCase());
The items of the input array are passed to a map function that returns a new array containing the lowercase values. There are some significant differences to note: the former example is less elegant and it requires more effort to be understood. The latter is terser and easier to read, which makes a huge difference in big code bases, where maintainability is crucial.
Another aspect worth mentioning is that, in the declarative example, there is no need to use variables nor to keep their values updated during the execution. Declarative programming tends to avoid creating and mutating a state.
As a final example, let's see what it means for React to be declarative.
The problem we will try to solve is a common task in web development: showing a map with a marker.
The JavaScript implementation (using the Google Maps SDK) is as follows:
const map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: myLatLng
});
const marker = new google.maps.Marker({
position: myLatLng,
title: 'Hello World!'
});
marker.setMap(map); It is imperative because all the instructions needed to create the map, and create the marker and attach it to the map, are described inside the code one after the other.
A React component to show a map on a page would look like this instead:
<Gmaps zoom={4} center={myLatLng}>
<Marker position={myLatLng} title="Hello world!" />
</Gmaps> In declarative programming, developers only describe what they want to achieve, and there's no need to list all the steps to make it work.
The fact that React offers a declarative approach makes it easy to use, and consequently, the resulting code is simple, which often leads to fewer bugs and more maintainability.
This book assumes that you are familiar with components and their instances, but there is another object you should know if you want to use React effectively – the element.
Whenever you call createClass, extend Component, or declare a stateless function, you are creating a component. React manages all the instances of your components at runtime, and there can be more than one instance of the same component in memory at a given point in time.
As mentioned previously, React follows a declarative paradigm, and there's no need to tell it how to interact with the DOM; you declare what you want to see on the screen and React does the job for you.
As you might have already experienced, most other UI libraries work oppositely: they leave the responsibility of keeping the interface updated to the developer, who has to manage the creation and destruction of the DOM elements manually.
To control the UI flow, React uses a particular type of object, called an element, that describes what has to be shown on the screen. These immutable objects are much simpler compared to the components and their instances, and contain only the information that is strictly needed to represent the interface.
The following is an example of an element:
{
type: Title,
props: {
color: 'red',
children: 'Hello, Title!'
}
} Elements have a type, which is the most important attribute, and some properties. There is also a particular property, called children, that is optional and represents the direct descendant of the element.
The type is important because it tells React how to deal with the element itself. If the type is a string, the element represents a DOM node, while if the type is a function, the element i...