Beginning React
eBook - ePub

Beginning React

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

Andrea Chiarelli

Share book
  1. 96 pages
  2. English
  3. ePUB (mobile friendly)
  4. Available on iOS & Android
eBook - ePub

Beginning React

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

Andrea Chiarelli

Book details
Book preview
Table of contents
Citations

About This Book

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.

Frequently asked questions

How do I cancel my subscription?
Simply head over to the account section in settings and click on “Cancel Subscription” - it’s as simple as that. After you cancel, your membership will stay active for the remainder of the time you’ve paid for. Learn more here.
Can/how do I download books?
At the moment all of our mobile-responsive ePub books are available to download via the app. Most of our PDFs are also available to download and we're working on making the final remaining ones downloadable now. Learn more here.
What is the difference between the pricing plans?
Both plans give you full access to the library and all of Perlego’s features. The only differences are the price and subscription period: With the annual plan you’ll save around 30% compared to 12 months on the monthly plan.
What is Perlego?
We are an online textbook subscription service, where you can get access to an entire online library for less than the price of a single book per month. With over 1 million books across 1000+ topics, we’ve got you covered! Learn more here.
Do you support text-to-speech?
Look out for the read-aloud symbol on your next book to see if you can listen to it. The read-aloud tool reads text aloud for you, highlighting the text as it is being read. You can pause it, speed it up and slow it down. Learn more here.
Is Beginning React an online PDF/ePUB?
Yes, you can access Beginning React by Andrea Chiarelli in PDF and/or ePUB format, as well as other popular books in Informatique & Programmation en JavaScript. We have over one million books available in our catalogue for you to explore.

Information

Year
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 of contents