Beginning React
eBook - ePub

Beginning React

Simplify your frontend development workflow and enhance the user experience of your applications with React

Andrea Chiarelli

Partager le livre
  1. 96 pages
  2. English
  3. ePUB (adapté aux mobiles)
  4. Disponible sur iOS et Android
eBook - ePub

Beginning React

Simplify your frontend development workflow and enhance the user experience of your applications with React

Andrea Chiarelli

DĂ©tails du livre
Aperçu du livre
Table des matiĂšres
Citations

À propos de ce livre

Take your web applications to a whole new level with efficient, component-based UIs that deliver cutting-edge interactivity and performance.

Key Features

  • Elaborately explains basics before introducing advanced topics
  • Explains creating and managing the state of components across applications
  • Implement over 15 practical activities and exercises across 11 topics to reinforce your learning

Book Description

Projects like Angular and React are rapidly changing how development teams build and deploy web applications to production. In this book, you'll learn the basics you need to get up and running with React and tackle real-world projects and challenges. It includes helpful guidance on how to consider key user requirements within the development process, and also shows you how to work with advanced concepts such as state management, data-binding, routing, and the popular component markup that is JSX. As you complete the included examples, you'll find yourself well-equipped to move onto a real-world personal or professional frontend project.

What you will learn

  • Understand how React works within a wider application stack
  • Analyze how you can break down a standard interface into specific components
  • Successfully create your own increasingly complex React components with HTML or JSX
  • Correctly handle multiple user events and their impact on overall application state
  • Understand the component lifecycle to optimize the UX of your application
  • Configure routing to allow effortless, intuitive navigation through your components

Who this book is for

If you are a frontend developer who wants to create truly reactive user interfaces in JavaScript, then this is the book for you. For React, you'll need a solid foundation in the essentials of the JavaScript language, including new OOP features that were introduced in ES2015. An understanding of HTML and CSS is assumed, and a basic knowledge of Node.js will be useful in the context of managing a development workflow, but is not essential.

Foire aux questions

Comment puis-je résilier mon abonnement ?
Il vous suffit de vous rendre dans la section compte dans paramĂštres et de cliquer sur « RĂ©silier l’abonnement ». C’est aussi simple que cela ! Une fois que vous aurez rĂ©siliĂ© votre abonnement, il restera actif pour le reste de la pĂ©riode pour laquelle vous avez payĂ©. DĂ©couvrez-en plus ici.
Puis-je / comment puis-je télécharger des livres ?
Pour le moment, tous nos livres en format ePub adaptĂ©s aux mobiles peuvent ĂȘtre tĂ©lĂ©chargĂ©s via l’application. La plupart de nos PDF sont Ă©galement disponibles en tĂ©lĂ©chargement et les autres seront tĂ©lĂ©chargeables trĂšs prochainement. DĂ©couvrez-en plus ici.
Quelle est la différence entre les formules tarifaires ?
Les deux abonnements vous donnent un accĂšs complet Ă  la bibliothĂšque et Ă  toutes les fonctionnalitĂ©s de Perlego. Les seules diffĂ©rences sont les tarifs ainsi que la pĂ©riode d’abonnement : avec l’abonnement annuel, vous Ă©conomiserez environ 30 % par rapport Ă  12 mois d’abonnement mensuel.
Qu’est-ce que Perlego ?
Nous sommes un service d’abonnement Ă  des ouvrages universitaires en ligne, oĂč vous pouvez accĂ©der Ă  toute une bibliothĂšque pour un prix infĂ©rieur Ă  celui d’un seul livre par mois. Avec plus d’un million de livres sur plus de 1 000 sujets, nous avons ce qu’il vous faut ! DĂ©couvrez-en plus ici.
Prenez-vous en charge la synthÚse vocale ?
Recherchez le symbole Écouter sur votre prochain livre pour voir si vous pouvez l’écouter. L’outil Écouter lit le texte Ă  haute voix pour vous, en surlignant le passage qui est en cours de lecture. Vous pouvez le mettre sur pause, l’accĂ©lĂ©rer ou le ralentir. DĂ©couvrez-en plus ici.
Est-ce que Beginning React est un PDF/ePUB en ligne ?
Oui, vous pouvez accĂ©der Ă  Beginning React par Andrea Chiarelli en format PDF et/ou ePUB ainsi qu’à d’autres livres populaires dans Informatique et Programmation en JavaScript. Nous disposons de plus d’un million d’ouvrages Ă  dĂ©couvrir dans notre catalogue.

Informations

Année
2018
ISBN
9781789534924

Managing User Interactivity

In this chapter, we are going to learn how to manage the events generated by a user's interaction with the components of a React-based user interface. We will explore the events that are triggered during the lifecycle of a React component, and will learn how to exploit them in order to create efficient components. Finally, we will use the React Router library to allow easy navigation between the different views implemented by components.
By the end of this chapter, you will be able to:
  • Handle events generated by user interaction
  • Change a component's state on event triggering
  • Use a component's lifecycle events for a better user experience
  • Configure routing to allow navigation through components

Managing User Interaction

Any web application requires interaction between the user and the user interface (UI). An application without interaction is not a true application; interactivity is a basic requirement.
The application that we built in the previous chapter does not allow interaction. It simply shows data, and the user cannot do anything with it (apart from look at it).
Suppose that we want to introduce a little interaction into the catalog application that we started building in the previous chapter. For example, perhaps we want to show an alert with the price of the product when the user clicks on the product area.
Provided that the product data includes the price, as in the following JSON object:
[
{"code":"P01",
"name": "Traditional Merlot",
"description": "A bottle of middle weight wine, lower in tannins
(smoother), with a more red-fruited flavor profile.",
"price": 4.5, "selected": false},
{"code":"P02",
"name": "Classic Chianti",
"description": "A medium-bodied wine characterized by a marvelous
freshness with a lingering, fruity finish",
"price": 5.3, "selected": false},
{"code":"P03",
"name": "Chardonnay",
"description": "A dry full-bodied white wine with spicy,
bourbon-y notes in an elegant bottle",
"price": 4.0, "selected": false},
{"code":"P04",
"name": "Brunello di Montalcino",
"description": "A bottle of red wine with exceptionally bold fruit
flavors, high tannin, and high acidity",
"price": 7.5, "selected": false}
]
We can implement this behavior as follows:
import React from 'react';

class Product extends React.Component {
showPrice() {
alert(this.props.item.price);
}

render() {
return <li onClick={() => this.showPrice()}>
<h3>{this.props.item.name}</h3>
<p>{this.props.item.description}</p>
</li>;
}
}

export default Product;
Let's analyze the component's code and highlight the differences with respect to the previous version.
First of all, we added the showPrice() method, showing the price of the current product instance via an alert. This method is invoked inside of an arrow function assigned to the onClick attribute of the <li> tag.
These simple changes allow the Product component to capture the click event and execute the showPrice() method.
We'll now open the existing project, my-shop-01, in order to show the result of the previous code changes:
  1. Open a console window
  2. Move to the my-shop-01 folder
  3. Run npm install
  4. Run npm start
The result of clicking on a product is shown in the following screenshot:

HTML Events versus React Events

As we can see, the React approach to handling events is very similar to classic event management within HTML. However, there are some subtle differences to take into account.
HTML events are named using lowercase, while JSX events use camelCase. For example, in HTML, you should use the following syntax:
<li onclick="...">...</li>
But in JSX, you use this syntax:
<li onClick=...>...</li>
In HTML, you assign a string representing the invocation of a function, while in JSX, you assign a function, which is shown as follows:
<li onclick="showPrice()">...</li>
<li onClick={showPrice}>...</li>
Of course, you can assign any JavaScript expression returning or representing a function, like the one shown in the following example:
<li onClick={() => this.showPrice()}>
Finally, you can prevent the default behavior of most HTML events by returning false, while in JSX events, you need to explicitly call preventDefault. The following is a typical example:
<a href="#" onClick={(e) => { e.preventDefault();
console.log("Clicked");}}>Click</a>

Event Handlers and the this Keyword

In the preceding example of defining a Product component, we assigned an arrow function to the onClick attribute, instead of the simple showPrice() method. This was not simply a matter of preference. It was necessary because we used the this keyword inside the showPrice() method.
In fact, when the event handler executes, the this keyword is no longer bound to the Product class, since it is asynchronously executed in a different context. This behavior does not depend on React, but on how JavaScript works.
In order to bind the method to the current class, we have a few options:
  1. Use an arrow function and invoke the method inside its body, as shown in the following example:
<li onClick={() => this.showPrice()}>
  1. Use the bind() method to bind the method to the current class context, as shown in the following example:
<li onClick={this.showPrice.bind(this)}>
  1. You can use bind() in the class constructor instead of using it inline when assigning the method to the event attribute. The following is an example of this approach:
constructor() {
this.showPrice = this.showPrice.bind(this);
}
...
<li onClick={this.showPrice}>

Changing the State

The event management example that we looked at is very simple, but it only shows the basics of React event management. This example does not involve the state, and its management is straightforward. In many real-world cases, an event causes changes to the application's state, and that means changes to the component's state.
Suppose that, for example, you want to allow the selecting of products from the catalog. To do so, we add the selected property to each product object, as shown in the following array:
[
{"code":"P01",
"name": "Traditional Merlot",
"description": "A bottle of middle weight wine, lower in tannins
(smoother), with a more red-fruited flavor profile.",
"price": 4.5, "selected": false},
{"code":"P02",
"name": "Classic Chianti",
"description": "A medium-bodied wine characterized by a marvelous
freshness with a lingering, fruity finish",
"price": 5.3, "selected": false},
{"code":"P03",
"name": "Chardonnay",
"description": "A dry full-bodied white wine...

Table des matiĂšres