Nothing Special   »   [go: up one dir, main page]

Discover millions of ebooks, audiobooks, and so much more with a free trial

Only $11.99/month after trial. Cancel anytime.

React and React Native: A complete hands-on guide to modern web and mobile development with React.js, 3rd Edition
React and React Native: A complete hands-on guide to modern web and mobile development with React.js, 3rd Edition
React and React Native: A complete hands-on guide to modern web and mobile development with React.js, 3rd Edition
Ebook947 pages5 hours

React and React Native: A complete hands-on guide to modern web and mobile development with React.js, 3rd Edition

Rating: 4 out of 5 stars

4/5

()

Read preview

About this ebook

Get up to speed with React, React Native, GraphQL and Apollo for building cross-platform native apps with the help of practical examples

Key Features



  • Covers the latest features of React such as Hooks, Suspense, NativeBase, and Apollo in this updated third edition
  • Get to grips with the React architecture for writing easy-to-manage web and mobile applications
  • Understand GraphQL and Apollo for building a scalable backend for your cross-platform apps

Book Description



React and React Native, Facebook's innovative User Interface (UI) libraries, are designed to help you build robust cross-platform web and mobile applications. This updated third edition is improved and updated to cover the latest version of React. The book particularly focuses on the latest developments in the React ecosystem, such as modern Hook implementations, code splitting using lazy components and Suspense, user interface framework components using Material-UI, and Apollo. In terms of React Native, the book has been updated to version 0.62 and demonstrates how to apply native UI components for your existing mobile apps using NativeBase.

You will begin by learning about the essential building blocks of React components. Next, you'll progress to working with higher-level functionalities in application development, before putting this knowledge to use by developing user interface components for the web and for native platforms. In the concluding chapters, you'll learn how to bring your application together with a robust data architecture.

By the end of this book, you'll be able to build React applications for the web and React Native applications for multiple mobile platforms.

What you will learn



  • Delve into the React architecture, component properties, state, and context
  • Get to grips with React Hooks for handling functions and components
  • Implement code splitting in React using lazy components and Suspense
  • Build robust user interfaces for mobile and desktop apps using Material-UI
  • Write shared components for Android and iOS mobile apps using React Native
  • Simplify layout design for React Native apps using NativeBase
  • Write GraphQL schemas to power web and mobile apps
  • Implement web and mobile components that are driven by Apollo

Who this book is for



This book is for any JavaScript developer who wants to start learning how to use Facebook's UI libraries, React and React Native, for mobile and web application development. Although no prior knowledge of React is needed, working knowledge of JavaScript programming will help you understand the concepts covered in the book more effectively.

LanguageEnglish
Release dateApr 30, 2020
ISBN9781839212437
React and React Native: A complete hands-on guide to modern web and mobile development with React.js, 3rd Edition

Read more from Boduch Adam

Related to React and React Native

Related ebooks

Internet & Web For You

View More

Related articles

Reviews for React and React Native

Rating: 4 out of 5 stars
4/5

2 ratings1 review

What did you think?

Tap to rate

Review must be at least 10 words

  • Rating: 4 out of 5 stars
    4/5
    To enhance its social media software, Facebook commissioned a JavaScript framework that makes clicking around on a website much more pleasureful for users. Instead of waiting for web servers to respond, the content requests are handled in the background and rendered by JavaScript on the client’s computer. This framework, called React, has become one of the leading UI frameworks available for web development today, along with Vue.js. This book introduces React.js and gets developers up-to-speed to write code to meet user needs.This book covers both React and React Native. React Native is oriented around developing mobile apps through JavaScript and JSX. I did not read this section as I’m primarily interested in using React for modern web development. Both use JSX – an extended and more powerful and expressive version of JavaScript.Boduch and Derks introduce the framework and coach readers on how to get started writing programs in the language. Code examples abound and are available for download on their GitHub site. In short time, I was able to code up a new web app in less time than it normally takes me with pure JavaScript. Because React is state driven and separates its data inputs from its rendering, the web app was able to be efficiently written without tons of tedious, detailed jQuery calls. I became aware of how pleasureful writing UI code could be for the programmer!Later chapters delve into specifics on how to build off of React into more interesting uses. For example, code for a simple client-side router is shown. Also, advanced UI design packages are presented along with examples of how to set up server-side React using Node.js and Express. React has a lot of potential applications, and the authors make it clear how different solutions can be implemented.This book’s main audience is software developers. Although the first chapter provides a high-level overview appropriate for IT business folk, the rest of the book uses many coding examples. Coding examples are great for software developers, but others will probably feel lost amidst all the detail. Readers should already be familiar with the basics of web development; this book merely builds on those foundations. Again, I cannot comment on the mobile development aspects either since those were not relevant for my needs. At around 500 pages and impressively in its third edition, this book provides a thorough overview for an emerging, hot technology. My biggest surprise is how fun React is to code in – always a good reaction when learning a language.

Book preview

React and React Native - Boduch Adam

React and React Native

React and React Native

Third Edition

A complete hands-on guide to modern web and mobile development with React.js

Adam Boduch

Roy Derks

BIRMINGHAM - MUMBAI

React and React Native Third Edition

Copyright © 2020 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the authors, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

Commissioning Editor: Ashwin Nair

Acquisition Editor: Ashitosh Gupta

Content Development Editor: Divya Vijayan

Senior Editor: Hayden Edwards

Technical Editor: Shubham Sharma

Copy Editor: Safis Editing

Project Coordinator: Kinjal Bari

Proofreader: Safis Editing

Indexer: Tejal Daruwale Soni

Production Designer: Nilesh Mohite

First published: March 2017

Second edition: September 2018

Third edition: April 2020

Production reference: 1290420

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham

B3 2PB, UK.

ISBN 978-1-83921-114-0

www.packt.com

Packt.com

Subscribe to our online digital library for full access to over 7,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.

Why subscribe?

Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals

Improve your learning with Skill Plans built especially for you

Get a free eBook or video every month

Fully searchable for easy access to vital information

Copy and paste, print, and bookmark content

Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.packt.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at customercare@packtpub.com for more details.

At www.packt.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks. 

Contributors

About the authors

Adam Boduch has been involved in large-scale JavaScript development for nearly 10 years. Before moving to the frontend, he worked on several large-scale cloud computing products using Python and Linux. No stranger to complexity, Adam has practical experience with real-world software systems and the scaling challenges they pose. He is the author of several JavaScript and React books and is passionate about innovative user experiences and high performance.

Roy Derks is a serial start-up CTO, conference speaker, and developer from Amsterdam. He has been actively programming since he was a teenager, starting as a self-taught programmer using online tutorials and books. At the age of 14, he founded his first start-up, a peer-to-peer platform where users could trade DVDs with other users for free. This marked the start of his career in web development, which back then primarily consisted of creating web applications using an MVC architecture with the LAMP stack. In 2015, he was introduced to React and GraphQL at a hackathon in Berlin, and after winning a prize for his project, he started to use these technologies professionally. Over the next few years, he helped multiple start-ups create cross-platform applications using React and React Native, including a start-up that he co-founded. He also started giving workshops and talks at conferences around the globe. In 2019, he gave over 20 conference talks about React, React Native, and GraphQL, inspiring over 10,000 developers worldwide.

About the reviewers

Emmanuel Demey works with the JavaScript ecosystem on a daily basis. He spends his time sharing his knowledge with anyone and everyone. His first goal at work is to help the people he works with. He has spoken at numerous French conferences (including Devfest Nantes, Devfest Toulouse, Sunny Tech, and Devoxx France) about topics related to the web platform, such as JavaScript frameworks (Angular, React.js, and Vue.js), accessibility, and Nest.js. He has been a trainer for 10 years at Worldline and Zenika (two French consulting companies). He is also the co-leader of the Google Developer Group de Lille and the co-organizer of the Devfest Lille conference.

Atul Sandilya Tiwari is working as Mobile Application Development Engineer since 2014. He has worked as a Software Engineer in several Silicon Valley startups. He has also been working as a React Native Development Engineer since 2017.

Packt is searching for authors like you

If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.

Table of Contents

Title Page

Copyright and Credits

React and React Native Third Edition

About Packt

Why subscribe?

Contributors

About the authors

About the reviewers

Packt is searching for authors like you

Preface

Who this book is for

What this book covers

Section 1 – React

Section 2 – React Native

Section 3 – React Architecture

To get the most out of this book

Download the example code files

Conventions used

Get in touch

Reviews

Section 1: React

Why React?

What is React?

React is just the view layer

Simplicity is good

Declarative UI structures

Time and data

Performance matters

The right level of abstraction

React Features

Revamped core architecture

Lifecycle methods

The Context API

Rendering fragments

Portals

Rendering lists and strings

Handling errors

Server-side rendering

What's new in React?

Memoizing functional components

Code splitting and loading

Hooks

Summary

Further reading

Rendering with JSX

Technical requirements

Your first JSX content

Hello JSX

Declarative UI structures

Rendering HTML

Built-in HTML tags

HTML tag conventions

Describing UI structures

Creating your own JSX elements

Encapsulating HTML

Nested elements

Namespaced components

Using JavaScript expressions

Dynamic property values and text

Mapping collections to elements

Fragments of JSX

Using wrapper elements

Using fragments

Summary

Further reading

Component Properties, State, and Context

Technical requirements

What is component state?

What are component properties?

Setting a component state

Setting an initial component state

Creating a component state

Merging the component state

Passing property values

Default property values

Setting property values

Stateless components

Pure functional components

Defaults in functional components

Container components

Providing and consuming context

Summary

Further reading

Getting Started with Hooks

Technical requirements 

Maintaining state using Hooks

Initial state values

Updating state values

Performing initialization and cleanup actions

Fetching component data

Canceling requests and resetting state

Optimizing side-effect actions

Sharing data using context Hooks

Sharing fetched data

Updating stateful context data

Using reducer Hooks to scale state management

Using reducer actions

Handling state dependencies

Summary

Event Handling - The React Way

Technical requirements

Declaring event handlers

Declaring handler functions

Multiple event handlers

Importing generic handlers

Using event handler context and parameters

Getting component data

Higher-order event handlers

Declaring inline event handlers

Binding handlers to elements

Using synthetic event objects

Understanding event pooling

Summary

Further reading

Crafting Reusable Components

Technical requirements 

Reusable HTML elements

The difficulty with monolithic components

The JSX markup

Initial state

Event handler implementation

Refactoring component structures

Starting with the JSX

Implementing an article list component

Implementing an article item component

Implementing an add article component

Making components functional

Render props

Refactoring class components using Hooks

Rendering component trees

Feature components and utility components

Summary

Further reading

The React Component Life Cycle

Technical requirements

Why components need a life cycle

Initializing properties and state

Fetching component data

Initializing state with properties

Updating state with properties

Optimizing rendering efficiency

To render or not to render

Using metadata to optimize rendering

Rendering imperative components

Rendering jQuery UI widgets

Cleaning up after components

Cleaning up asynchronous calls

Containing errors with error boundaries

Summary

Further reading

Validating Component Properties

Technical requirements

Knowing what to expect

Promoting portable components

Simple property validators

Basic type validation

Requiring values

Any property value

Type and value validators

Things that can be rendered

Requiring specific types

Requiring specific values

Writing custom property validators

Summary

Further reading

Handling Navigation with Routes

Technical requirements

Declaring routes

Hello route

Decoupling route declarations

Parent and child routes

Handling route parameters

Resource IDs in routes

Optional parameters

Using link components

Basic linking

URL and query parameters

Summary

Further reading

Code Splitting Using Lazy Components and Suspense

Technical requirements

Using the lazy API

Dynamic imports and bundles

Making components lazy

Using the Suspense component

Top-level Suspense components

Simulating latency

Working with spinner fallbacks

When to avoid lazy components

Lazy pages and routes

Summary

Server-Side React Components

Technical requirements

What is isomorphic JavaScript?

The server is a render target

Initial load performance

Sharing code between the server and the browser

Rendering to strings

Backend routing

Frontend reconciliation

Fetching data

Summary

Further reading

User Interface Framework Components

Technical requirements 

Layout and organization

Using containers

Building responsive grid layouts

Using navigation components

Navigating with drawers

Navigating with tabs

Collecting user input

Checkboxes and radio buttons

Text inputs and select inputs

Working with buttons

Working with styles and themes

Making styles

Customizing themes

Summary

Section 2: React Native

Why React Native?

Technical requirements

What is React Native?

React and JSX are familar

The mobile browser experience

Android and iOS – different yet the same

The case for mobile web apps

Summary

Further reading

Kick-Starting React Native Projects

Technical requirements

Installing and using the Expo command-line tool

Viewing your app on your phone

Viewing your app on Expo Snack

Summary

Building Responsive Layouts with Flexbox

Technical requirements

Flexbox is the new layout standard

Introducing React Native styles

Building Flexbox layouts

Simple three-column layout

Improved three-column layout

Flexible rows

Flexible grids

Flexible rows and columns

Summary

Further reading

Navigating Between Screens

Technical requirements

Navigation basics

Route parameters

The navigation header

Tab and drawer navigation

Handling state

Summary

Further reading

Rendering Item Lists

Technical requirements 

Rendering data collections

Sorting and filtering lists

Fetching list data

Lazy list loading

Summary

Further reading

Showing Progress

Technical requirements

Progress and usability

Indicating progress

Measuring progress

Navigation indicators

Step progress

Summary

Further reading

Geolocation and Maps

Technical requirements 

Where am I?

What's around me?

Annotating points of interest

Plotting points

Plotting overlays

Summary

Further reading

Collecting User Input

Technical requirements

Collecting text input

Selecting from a list of options

Toggling between on and off

Collecting date/time input

Summary

Further reading

Displaying Modal Screens

Technical requirements

Important information

Getting user confirmation

Displaying a success confirmation

Error confirmation

Passive notifications

Activity modals

Summary

Further reading

Responding to User Gestures

Technical requirements

Scrolling with your fingers

Giving touch feedback

Swipeable and cancellable

Summary

Further reading

Controlling Image Display

Technical requirements

Loading images

Resizing images

Lazy image loading

Rendering icons

Summary

Further reading

Going Offline

Technical requirements

Detecting the state of the network

Storing application data

Synchronizing application data

Summary

Further reading

Section 3: React Architecture

Native UI Components Using NativeBase

Technical requirements

Application containers

Headers, footers, and navigation

Using layout components

Collecting input using form components

Displaying data using lists

Showing user notifications

Summary

Handling Application State

Technical requirements

Information architecture and Flux

Unidirectionality

Synchronous update rounds

Predictable state transformations

Unified information architecture

Implementing Redux

Initial application state

Creating the store

Store provider and routes

The App component

The Home component

State in mobile apps

Scaling the architecture

Summary

Further reading

Why Apollo?

Yet another approach?

Verbose vernacular

Declarative data fetching

Mutating application state

Summary

Further reading

Building an Apollo React App

Technical requirements

Todo and Apollo Client

The GraphQL schema

Bootstrapping Apollo Client

Adding todo items

Rendering todo items

Completing todo items

Summary

Other Books You May Enjoy

Leave a review - let other readers know what you think

Preface

I never had any interest in developing mobile apps. I used to believe strongly that it was the web, or nothing; that there was no need for yet more applications to install on devices already overflowing with apps. Then, React Native came along. I was already writing React code for web applications and loving it. It turns out that I wasn't the only developer that balked at the idea of maintaining several versions of the same app using different tooling, environments, and programming languages. React Native was created out of a natural desire to take what works well from a web development experience standpoint (React), and apply it to native app development. Native mobile apps offer better user experiences than web browsers. It turns out I was wrong; we do need mobile apps for the time being. But that's okay, because React Native is a fantastic tool. This book is essentially my experience as a React developer for the web and as a less experienced mobile app developer. React Native is meant to be an easy transition for developers who already understand React for the web. With this book, you'll learn the subtleties of doing React development in both mobile and web environments. You'll also learn the conceptual theme of React, a simple rendering abstraction that can target anything. Today, it's web browsers and mobile devices. Tomorrow, it could be anything.

The second edition of this book was written to address the rapidly evolving React project-including state-of-the-art best practices for implementing React components as well as the ecosystem surrounding React. I think it's important for React developers to appreciate how React works and how the implementation of React changes to better support the people who rely on it. I've done my best to capture the essence of React as it is today and the direction in which it's moving, in this edition of React and React Native.

Who this book is for

This book is written for any JavaScript developer—beginner or expert—who wants to start learning how to put both of Facebook's UI libraries to work. No knowledge of React is required, although a working knowledge of ECMAScript (ES) will help you follow along better.

What this book covers

This book covers the following three sections:

React: Chapters 1 to 12

React Native: Chapters 13 to 24

React Architecture: Chapters 25 to 28

Section 1 – React

Chapter 1, Why React?, covers the basics of what React really is, and why you want to use it.

Chapter 2, Rendering with JSX, explains that JSX is the syntax used by React to render content. HTML is the most common output, but JSX can be used to render many things, such as native UI components.

Chapter 3, Component Properties, State, and Context, shows how properties are passed to components, how state re-renders components when it changes, and the role of context in components.

Chapter 4, Getting Started with Hooks, gets you moving with the new Hooks React API that replaces many legacy React APIs.

Chapter 5, Event Handling – The React Way, explains that events in React are specified in JSX. There are subtleties associated with how React processes events, and how your code should respond to them.

Chapter 6, Crafting Reusable Components, shows that components are often composed using smaller components. This means that you have to properly pass data and behavior to child components.

Chapter 7, The React Component Life Cycle, explains how React components are created and destroyed all the time. There are several other life cycle events that take place in between, where you do things such as fetch data from the network.

Chapter 8, Validating Component Properties, shows that React has a mechanism that allows you to validate the types of properties that are passed to components. This ensures that there are no unexpected values passed to your component.

Chapter 9, Handling Navigation with Routes, explains that navigation is an essential part of any web application. React handles routes declaratively using the react-router package.

Chapter 10, Code Splitting Using Lazy Components and Suspense, shows you how to structure your components so that only code that's needed is loaded into the browser.

Chapter 11, Server-Side React Components, discusses how React renders components to the DOM when rendered in the browser. It can also render components to strings, which is useful for rendering pages on the server and sending static content to the browser.

Chapter 12, User Interface Framework Components, introduces you to the popular Material-UI React framework for building responsive UIs.

Section 2 – React Native

Chapter 13, Why React Native?, shows that React Native is React for mobile apps. If you've already invested in React for web applications, then why not leverage the same technology to provide a better mobile experience?

Chapter 14, Kick-Starting React Native Projects, discusses how nobody likes writing boilerplate code or setting up project directories. React Native has tools to automate these mundane tasks.

Chapter 15, Building Responsive Layouts with Flexbox, explains why the Flexbox layout model is popular with web UI layouts using CSS. React Native uses the same mechanism to lay out screens.

Chapter 16, Navigating Between Screens, discusses the fact that while navigation is an important part of web applications, mobile applications also need tools to handle how a user moves from one screen to the next.

Chapter 17, Rendering Item Lists, demonstrates that React Native has a list view component that's perfect for rendering lists of items. You simply provide it with a data source, and it handles the rest.

Chapter 18, Showing Progress, explains that progress bars are great for showing a specified amount of progress. When you don't know how long something will take, you use a progress indicator. React Native has both of these components.

Chapter 19, Geolocation and Maps, shows that the react-native-maps package provides React Native with mapping capabilities. The Geolocation API that's used in web applications is provided directly by React Native.

Chapter 20, Collecting User Input, shows that most applications need to collect input from the user. Mobile applications are no different, and React Native provides a variety of controls that are not unlike HTML form elements.

Chapter 21, Displaying Modal Screens, explains that alerts are designed to interrupt the user to let them know something important has happened, while notifications are unobtrusive updates, and confirmation is used to get an immediate answer.

Chapter 22, Responding to User Gestures, discusses how gestures on mobile devices are something that's difficult to get right in the browser. Native apps, on the other hand, provide a much better experience for swiping, touching, and so on. React Native handles a lot of the details for you.

Chapter 23, Controlling Image Display, shows how images play a big role in most applications, either as icons, logos, or photographs of things. React Native has tools for loading images, scaling them, and placing them appropriately.

Chapter 24, Going Offline, explains that mobile devices tend to have volatile network connectivity. Therefore, mobile apps need to be able to handle temporary offline conditions. For this, React Native has local storage APIs.

Section 3 – React Architecture

Chapter 25, Native UI Components Using NativeBase, shows you how to build native user interfaces using pre-built, platform-agnostic UI components.

Chapter 26, Handling Application State, discusses how application state is important for any React application, web or mobile. This is why understanding libraries such as Redux and Immutable.js is important.

Chapter 27, Why Apollo?, explains that Apollo and GraphQL, used together, represent a novel approach to handling state at scale. It is a query and mutation language, plus a library for wrapping React components.

Chapter 28, Building an Apollo React App, shows that the real advantage of Apollo and GraphQL lies in the fact that your state schema is shared between web and native versions of your application.

To get the most out of this book

As you go through the book, you will uncover how all the concepts come together when building web and mobile applications with React. 

All code examples have been tested using React 16.13, React Native 0.62, Node.js 14.

Before you start, you will need the following things set up:

A code editor

A modern web browser

Node.js

If you are using the digital version of this book, we advise you to type the code yourself or access the code via the GitHub repository (link available in the next section). Doing so will help you avoid any potential errors related to the copying and pasting of code.

Download the example code files

You can download the example code files for this book from your account at www.packt.com. If you purchased this book elsewhere, you can visit www.packtpub.com/support and register to have the files emailed directly to you.

You can download the code files by following these steps:

Log in or register at www.packt.com.

Select the SUPPORT tab.

Click on Code Downloads.

Enter the name of the book in the Search box and follow the onscreen instructions.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

WinRAR/7-Zip for Windows

Zipeg/iZip/UnRarX for Mac

7-Zip/PeaZip for Linux

The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/React-and-React-Native---Third-Edition. In case there's an update to the code, it will be updated on the existing GitHub repository.

We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Conventions used

There are a number of text conventions used throughout this book.

CodeInText: Indicates code words in text, database table names, folder names, filenames, file extensions, path names, dummy URLs, user input, and Twitter handles. Here is an example: The Query component takes a GraphQL query as a prop and returns an object with the state variables, loading, error, and data.

A block of code is set as follows:

import React, { Component } from 'react';

// Renders a

// this.props.children as the text.

export default class MyButton extends Component {

  render() {

    return ;

  }

}

Any command-line input or output is written as follows:

$ npm install -g create-react-native-app

$ create-react-native-app my-project

Bold: Indicates a new term, an important word, or words that you see on screen. For example, words in menus or dialog boxes appear in the text like this. Here is an example: Select System info from the Administration panel.

Warnings or important notes appear like this.

Tips and tricks appear like this.

Get in touch

Feedback from our readers is always welcome.

General feedback: If you have questions about any aspect of this book, mention the book title in the subject of your message and email us at customercare@packtpub.com.

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/support/errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.

Piracy: If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at copyright@packt.com with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in, and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.

Reviews

Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!

For more information about Packt, please visit packt.com.

Section 1: React

In this section, we will cover the following chapters:

Chapter 1,Why React?

Chapter 2,Rendering with JSX

Chapter 3,Component Properties, State, and Context

Chapter 4, Getting Started with Hooks

Chapter 5,Event Handling – the React Way

Chapter 6,Crafting Reusable Components

Chapter 7,The React Component Life Cycle

Chapter 8,Validating Component Properties

Chapter 9,Handling Navigation with Routes

Chapter 10,Code Splitting Using Lazy Components and Suspense

Chapter 11, Server-Side React Components

Chapter 12, User Interface Framework Components

Why React?

If you're reading this book, you probably know what React is. If not, don't worry. I'll do my best to keep philosophical definitions to a minimum. However, this is a long book with a lot of content, so I feel that setting the tone is an appropriate first step. Yes, the goal is to learn React and React Native. But it's also to put together a lasting architecture that can handle everything we want to build with React today and in the future.

This chapter starts with a brief explanation of why React exists. Then, we'll think about the simplicity of React and how React is able to handle many of the typical performance issues faced by web developers. Next, we'll go over the declarative philosophy of React and the level of abstraction that React programmers can expect to work with. Finally, we'll touch on some of the major features of React.

Once you have a conceptual understanding of React and how it solves problems with UI development, you'll be better equipped to tackle the remainder of the book.

This chapter will cover the following topics:

What is React?

React Features

What's new in React?

What is React?

I think the one-line description of React on its home page (https://facebook.github.io/react) is concise and accurate:

A JavaScript library for building user interfaces.

It's a library for building user interfaces (UIs). This is perfect because, as it turns out, this is all we want most of the time. I think the best part about this description is everything that it leaves out. It's not a mega framework. It's not a full-stack solution that's going to handle everything from the database to real-time updates over WebSocket connections. We might not actually want most of these prepackaged solutions.

If React isn't a framework, then what is it exactly?

React is just the view layer

React is generally thought of as the view layer in an application. You might have used a library such as Handlebars or jQuery in the past. Just like jQuery manipulates UI elements and Handlebars templates are inserted into the page, React components change what the user sees. The following diagram illustrates where React fits in our frontend code:

This is all there is to React—the core concept. Of course, there will be subtle variations to this theme as we make our way through the book, but the flow is more or less the same. We have some application logic that generates some Data. We want to render this Data to the UI, so we pass it to a React Component, which handles the job of getting the HTML into the page.

You may wonder what the big deal is; React appears to be yet another rendering technology. We'll touch on some of the key areas where React can simplify application development in the remaining sections of the chapter.

Simplicity is good

React doesn't have many moving parts to learn about and understand. Internally, there's a lot going on, and we'll touch on these things throughout the book. The advantage of having a small API to work with is that you can spend more time familiarizing yourself with it, experimenting with it, and so on. The opposite is true of large frameworks, where all of your time is devoted to figuring out how everything works. The following diagram gives you a rough idea of the APIs that we have to think about when programming with React:

React is divided into two major APIs:

The React Component API: These are the parts of the page that are actually rendered by React DOM.

React DOM: This is the API that's used to perform the actual rendering on a web page.

Within a React component, we have the following areas to think about:

Data: This is data that comes from somewhere (the component doesn't care where), and is rendered by the component.

Lifecycle: This consists of methods or Hooks that we implement to respond to the component's entering and exiting phases of the React rendering process as they happen over time. For example, one phase of the lifecycle is when the component is about to be rendered.

Events: These are the code that we write for responding to user interactions.

JSX: This is the syntax of React components used to describe UI structures.

Don't fixate on what these different areas of the React API represent just yet. The takeaway here is that React, by nature, is simple. Just look at how little there is to figure out! This means that we don't have to spend a ton of time going through API details here. Instead, once you pick up on the basics, we can spend more time on nuanced React usage patterns that fit in nicely with declarative UI structures.

Declarative UI structures

React newcomers have a hard time coming to grips with the idea that components mix markup in with their JavaScript in order to declare UI structures. If you've looked at React examples and had the same adverse reaction, don't worry. Initially, we're all skeptical of this approach, and I think the reason is that we've been conditioned for decades by the separation of concerns principle. This principle states that different concerns, such as logic and presentation, should be separate from one another. Now, whenever we see things mixed together, we automatically assume that this is bad and shouldn't happen.

The syntax used by React components is called JSX (JavaScript XML). A component renders content by returning some JSX. The JSX itself is usually HTML markup, mixed with custom tags for React components. The specifics don't matter at this point; we'll go into detail in the coming chapters. What's groundbreaking about the declarative JSX approach is that we don't have to perform little micro-operations to change the content of a component.

Although I won't be following the convention in this book, some React developers prefer the .jsx extension instead of .js for their components.

For example, think about using something like jQuery to build your application. You have a page with some content on it, and you want to add a class to a paragraph when a button is clicked. Performing these steps is easy enough. This is called imperative programming, and it's problematic for UI development. While this example of changing the class of an element is simple, real applications tend to involve more than three or four steps to make something happen.

React components don't require executing steps in an imperative way. This is why JSX is central to React components. The XML-style syntax makes it easy to describe what the UI should look like. That is, what are the HTML elements that this component is going to render? This is called declarative programming and is very well suited for UI development. Once you've declared your UI structure, you need to specify how it changes over time.

Time and data

Another

Enjoying the preview?
Page 1 of 1