Reader small image

You're reading from  Beginning React

Product typeBook
Published inJul 2018
Reading LevelBeginner
Publisher
ISBN-139781789530520
Edition1st Edition
Languages
Tools
Right arrow
Author (1)
Andrea Chiarelli
Andrea Chiarelli
author image
Andrea Chiarelli

Andrea Chiarelli has over 20 years experience as a software engineer and technical writer. In his professional career, he has used various technologies for the projects he has been involved in: from C# to JavaScript, from Angular to React, from ASP.NET to PhoneGap/Cordova. He has contributed to many online and offline magazines and has been the author of a few books published by Wrox Press and Packt. Currently, he is a senior software engineer at the Italian office of Apparound, Inc. and a regular contributor to HTML.it, an Italian online magazine focused on web technologies. You can follow him on Twitter at @andychiare.
Read more about Andrea Chiarelli

Right arrow

Chapter 2. Creating Components

In this chapter, we are going to learn how to implement React components, how to assemble multiple components into one, and how to manage their internal states. We will explore React component implementation by building a simple application. This application will be implemented step-by-step, in order to put the outlined concepts into practice.

By the end of this chapter, you will be able to:

  • Create basic React components
  • Use JSX to define a component's markup
  • Combine multiple React components in order to create complex UI elements
  • Manage the internal state of React components

Definition of a Component


As defined in the previous chapter, components are the fundamental building blocks of React. Virtually any visual item in a user interface can be a component. From a formal point of view, we would say that a React component is a piece of JavaScript code defining a portion of a user interface.

Consider the following code in a file:

import React from 'react';

class Catalog extends React.Component {
  render() {
    return <div><h2>Catalog</h2></div>;
  }
}

export default Catalog;

This is an ECMAScript 2015 module, defining a basic React component.

It imports the React namespace from the react module and defines the Catalog class by extending the React.Component class. The module exports the Catalog class as a default export.

The interesting part of this definition is the implementation of the render() method.

The render() method defines the visual part of the component. It may execute any JavaScript code, and it should return a markup expression...

Using JSX


In previous examples, we defined the visual output returned by the render() method of a component by using an HTML-like markup expression. Let's see, for example, the definition of the Catalog component:

import React from 'react';
import './Catalog.css';

class Catalog extends React.Component {
  render() {
    return <div><h2>Catalog</h2></div>;
  }
}

export default Catalog;

The markup expression is not using JavaScript syntax, but it is included inside of a JavaScript code snippet. Why do we mix HTML and JavaScript syntaxes? How is that possible?

Let's start by saying that the HTML-like language describing the React component's visual output is called JSX. This language extends JavaScript with XML expressions in order to simplify the creation of HTML elements within JavaScript code. You may think of it as a sort of document.write("..."), but much more powerful. In fact, when building a React application, the JSX markup is pre-processed by a specific parser...

Composing Components


When defining React components, we can use them as the children of another component by using that component as a React element. We already saw this when we included the Catalog component inside of the App component, but let's analyze this composition further.

Combining Components

We will now see how to combine components in order to create new, complex components:

  1. Open the src/ProductList.js file in the my-shop-03 folder
  2. Follow the text until the end of the section

Let's consider the following component:

import React from 'react';
class ProductList extends React.Component {
  render() {
    return <ul>
      <li>
        <h3>Traditional Merlot</h3>
        <p>A bottle of middle weight wine, lower in tannins (smoother), 
           with a more red-fruited flavor profile.</p>
      </li>
      <li>
        <h3>Classic Chianti</h3>
        <p>A medium-bodied wine characterized by a marvelous freshness with 
 ...

Data Propagation


The ProductList component that we defined in the previous section is impractical. Let's take a look at it again:

import React from 'react';
import './ProductList.css';

class ProductList extends React.Component {
  render() {
    return <ul>
      <li>
        <h3>Traditional Merlot</h3>
        <p>A bottle of middle weight wine, lower in tannins (smoother), 
           with a more red-fruited flavor profile.</p>
      </li>
      <li>
        <h3>Classic Chianti</h3>
        <p>A medium-bodied wine characterized by a marvelous freshness with 
           a lingering, fruity finish</p>
      </li>
      <li>
        <h3>Chardonnay</h3>
        <p>A dry full-bodied white wine with spicy, bourbon-y notes in an 
           elegant bottle</p>
      </li>
      <li>
        <h3>Brunello di Montalcino</h3>
        <p>A bottle of red wine with...

Managing the Internal State


Components have the ability to store data that can change over time.

When a component shows data that can change over time, we want changes to be shown as soon as possible. For example, consider the ProductList component: it shows a list of products contained in the products array. If a new product is added to the array, we want it to be shown immediately. React provides a mechanism to support the automatic rendering of a component when data changes. Such a mechanism is based on the concept of state.

Note

React state is a property that represents data that changes over time. Every component supports the state property, but it should be used carefully.

Again, consider the ProductList component:

import React from 'react';
import Product from './Product';

class ProductList extends React.Component {
  render() {
    let products = [
      {code:"P01", name: "Traditional Merlot", description: "A bottle
       of middle weight wine, lower in tannins (smoother), with a more...

Summary


In this chapter, we started to create React components and explored their basic features. In particular, we:

  • Learned how to define a component as a class derived from React.Component, and how to import specific CSS styles
  • Explored the syntax of JSX, which allows us to quickly define the graphical aspect of a component and use React components that were defined elsewhere
  • Combined React components in order to build other components
  • Used state management features so that React components automatically update their visual representation when data changes

In the next chapter, we will analyze how to manage user interaction with a React-based application; in other words, how to capture events and make a UI react to those events.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Beginning React
Published in: Jul 2018Publisher: ISBN-13: 9781789530520
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at AU $19.99/month. Cancel anytime

Author (1)

author image
Andrea Chiarelli

Andrea Chiarelli has over 20 years experience as a software engineer and technical writer. In his professional career, he has used various technologies for the projects he has been involved in: from C# to JavaScript, from Angular to React, from ASP.NET to PhoneGap/Cordova. He has contributed to many online and offline magazines and has been the author of a few books published by Wrox Press and Packt. Currently, he is a senior software engineer at the Italian office of Apparound, Inc. and a regular contributor to HTML.it, an Italian online magazine focused on web technologies. You can follow him on Twitter at @andychiare.
Read more about Andrea Chiarelli