Beginning React
eBook - ePub

Beginning React

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

Andrea Chiarelli

Condividi libro
  1. 96 pagine
  2. English
  3. ePUB (disponibile sull'app)
  4. Disponibile su iOS e Android
eBook - ePub

Beginning React

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

Andrea Chiarelli

Dettagli del libro
Anteprima del libro
Indice dei contenuti
Citazioni

Informazioni sul libro

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.

Domande frequenti

Come faccio ad annullare l'abbonamento?
È semplicissimo: basta accedere alla sezione Account nelle Impostazioni e cliccare su "Annulla abbonamento". Dopo la cancellazione, l'abbonamento rimarrà attivo per il periodo rimanente già pagato. Per maggiori informazioni, clicca qui
È possibile scaricare libri? Se sì, come?
Al momento è possibile scaricare tramite l'app tutti i nostri libri ePub mobile-friendly. Anche la maggior parte dei nostri PDF è scaricabile e stiamo lavorando per rendere disponibile quanto prima il download di tutti gli altri file. Per maggiori informazioni, clicca qui
Che differenza c'è tra i piani?
Entrambi i piani ti danno accesso illimitato alla libreria e a tutte le funzionalità di Perlego. Le uniche differenze sono il prezzo e il periodo di abbonamento: con il piano annuale risparmierai circa il 30% rispetto a 12 rate con quello mensile.
Cos'è Perlego?
Perlego è un servizio di abbonamento a testi accademici, che ti permette di accedere a un'intera libreria online a un prezzo inferiore rispetto a quello che pagheresti per acquistare un singolo libro al mese. Con oltre 1 milione di testi suddivisi in più di 1.000 categorie, troverai sicuramente ciò che fa per te! Per maggiori informazioni, clicca qui.
Perlego supporta la sintesi vocale?
Cerca l'icona Sintesi vocale nel prossimo libro che leggerai per verificare se è possibile riprodurre l'audio. Questo strumento permette di leggere il testo a voce alta, evidenziandolo man mano che la lettura procede. Puoi aumentare o diminuire la velocità della sintesi vocale, oppure sospendere la riproduzione. Per maggiori informazioni, clicca qui.
Beginning React è disponibile online in formato PDF/ePub?
Sì, puoi accedere a Beginning React di Andrea Chiarelli in formato PDF e/o ePub, così come ad altri libri molto apprezzati nelle sezioni relative a Computer Science e Programming in JavaScript. Scopri oltre 1 milione di libri disponibili nel nostro catalogo.

Informazioni

Anno
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...

Indice dei contenuti