The

React

Workshop

The React Workshop 

Copyright © 2020 Packt Publishing

All rights reserved. No part of this course 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 course to ensure the accuracy of the information presented. However, the information contained in this course is sold without warranty, either express or implied. Neither the authors, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this course.

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

Authors: Brandon Richey, Ryan Yu, Endre Vegh, Theofanis Despoudis, Anton Punith, and Florian Sloot

Reviewers: Souvik Basu, Daniel Bugl, Brandan Jones, SudarshanReddy Kurri, David Parker, and Cihan Yakar

Managing Editor: Ranu Kundu

Acquisitions Editors: Anindya Sil, Sneha Shinde, Alicia Wooding, Archie Vankar, and Karan Wadekar

Production Editor: Shantanu Zagade

Editorial Board: Megan Carlisle, Samuel Christa, Mahesh Dhyani, Heather Gopsill, Manasa Kumar, Alex Mazonowicz, Monesh Mirpuri, Bridget Neale, Dominic Pereira, Shiny Poojary, Abhishek Rane, Brendan Rodrigues, Erol Staveley, Ankita Thakur, Nitesh Thakur, and Jonathan Wray

First published: August 2020

Production reference: 1210820

ISBN: 978-1-83864-556-4

Published by Packt Publishing Ltd.

Livery Place, 35 Livery Street

Birmingham B3 2PB, UK

Table of Contents

Preface   i

1. Getting Started with React   1

Introduction   2

Problems before React   2

Introducing React   5

Getting Started with Create React App   6

Setting Up a Development Environment    7

Tweaking Create React App's Options    9

Using Create React App to Create Our Project   10

Exploring the Created Project   13

Exploring the Rest of the Scaffold   17

Introduction to JSX   18

Diving Deeper into JSX   19

Exercise 1.01: Implementing JSX    21

Creating a React Component   23

Preparing Our Code to Start Writing Our Component   23

Understanding Props   24

Exercise 1.02: Creating Our First React Component   26

Understanding React Rendering   28

Building Components with Classes   30

Exercise 1.03: Implementing a Click Counter in React Using Classes   30

Activity 1.01: Design a React Component   34

Summary   36

2. Dealing with React Events   39

Introduction – Talking to JavaScript with React   40

Designing the State of Our Application   41

Quick UI Examples   42

Getting Started – Building Our Baseline Component   45

Exercise 2.01: Writing the Starter State for Our Code   47

Event Handlers in React   49

onClick   50

Exercise 2.02: Writing Our First Event Handler   50

onBlur   53

Context of Event Handlers   55

In-line Bind Statements   57

Constructor Bind Statements   58

Exercise 2.03: Building our Username Validator   59

Exercise 2.04: Using Alternative Class Declarations to Avoid Binds   61

Form Validation in React   64

Exercise 2.05: Creating a Validation for Input Fields   65

Activity 2.01: Create a Blog Post Using React Event Handlers   70

Summary   71

3. Conditional Rendering and for Loops   73

Introduction   74

Conditional Rendering   74

Exercise 3.01: Building Our First App Using Conditional Rendering   76

Nested Conditional Rendering   82

Exercise 3.02: Building a Conditional Quiz App   83

Rendering Loops with React   92

Rendering Loops   94

Exercise 3.03: Refining Our Quiz Display with Loops   96

Activity 3.01: Building a Board Game Using Conditional Rendering   99

Summary   102

4. React Lifecycle Methods   105

Introduction   106

Overview of the Component Lifecycle    106

Exercise 4.01: Implementing Lifecycle Methods   109

The Mount Lifecycle   112

constructor()   113

Exercise 4.02: Conditional Rendering and the Mount Lifecycle   113

render()   116

componentDidMount()   117

The Update Lifecycle   118

render()   118

componentDidUpdate()   118

Exercise 4.03: Simulating a Slow AJAX Request and Prerendering Your Component   119

The Unmount Lifecycle   123

componentWillUnmount()   124

Exercise 4.04: Messaging on Unmount   125

Activity 4.01: Creating a Messaging App    129

Summary   131

5. Class and Function Components   133

Introduction   134

Introduction to Thinking with React Components   134

Atomic Design   134

Pragmatic Approach   136

Building React Components   139

Data Flow   140

State and Props   140

Class Components   140

Exercise 5.01: Creating Profile Component as a Class Component   143

Function Component   151

Exercise 5.02: Changing the Loader Component as a Function Component   152

Differences between Class and Function Components   159

Syntax   159

Handling State   161

Activity 5.01: Creating a Comments Section   163

Summary   166

6. State and Props   169

Introduction   170

State in React   170

Initializing and Using State   171

Setting State 171

setState 172

Custom Methods and Closure   172

Exercise 6.01: Building an App to Change the Theme   173

Props in React   178

Children Prop   179

Props are Immutable 179

Exercise 6.02: Creating a Modal Screen   180

Activity 6.01: Creating a Products App Page   191

Summary   193

7. Communication between Components   195

Introduction   196

Getting Started   198

Passing Data from Parent to Child Components   200

Passing Data to Direct Child Components   201

Example 1: Sending Data from a Parent Component to a Direct Child Component   201

Example 2: Receiving Data in a Child Class Component   202

Example 3: Receiving Data in a Child Function Component   204

Example 4: Sending number and Boolean as Props from the Parent Component   205

Example 5: Receiving number and boolean Values in Class-Based and Functional Components   206

Destructuring Props 208

Example 6: Destructuring Prop Values in a Child Class Component   209

Example 7: Destructuring Prop Values in a Function Component   211

Exercise 7.01: Sending and Receiving Objects as Props from the Parent    212

The {children} Prop   215

Exercise 7.02: Sending Child Elements Using the children Prop   216

Sending and Receiving an Array through Props   217

Exercise 7.03: Sending, Receiving, and Displaying an Array from a Parent to a Child    221

Passing Data to a Child Component Multiple Levels Down   226

Splitting a Component into Smaller Components 228

Exercise 7.04: Splitting into Smaller Components   229

Passing a Component through a Prop   230

Exercise 7.05: Creating a Photo Function Component   232

Higher-Order Components   235

Exercise 7.06: Creating a HOC Function That Can Be Called with DonationColor   237

Render Props    241

Exercise 7.07: Adding donationColor   241

Passing Data from Children to a Parent   247

Exercise 7.08: Passing Data from a Child to a Parent Component   249

Passing Data Between Components at Any Level   253

Exercise 7.09: Adding the addList Callback Function   256

The Context API   262

Exercise 7.10: Creating the <AnimalCount> Component Using the React Context API   265

Activity 7.01: Creating a Temperature Converter   269

Summary   272

8. Introduction to Formik   275

Introduction   276

Uncontrolled Components   276

Exercise 8.01: Creating Our First Uncontrolled Form Component   278

Controlled Components   281

Exercise 8.02: Converting Our Form Component from Uncontrolled to Controlled   282

Introduction to Formik   285

Advantages of Formik   286

Anatomy of a Formik Component   286

Initial Values and Handlers   290

Formik Higher-Order Components   292

Connect   294

Validating a Form   294

Exercise 8.03: Adding Field Validators   295

Controlling When Formik Runs Validation Rules   297

Schema Validation   298

Exercise 8.04: Controlling Schema Validation Phases   300

Submitting a Form   303

Activity 8.01: Writing Your Own Form Using Formik   305

Summary   307

9. Introduction to React Router   309

Introduction   310

Understanding Browser Routing    310

Exercise 9.01: Building a Basic Router using the Location API   311

Basics of React Router   316

Exercise 9.02: Implementing a Switch Router   317

Adding Params to Your Routes   320

Exercise 9.03: Adding Params to Routes   321

Adding Page Not Found for Routes   325

Exercise 9.04: Adding a NotFound Route   326

Nesting Routes   328

Exercise 9.05: Nested Routes and the Link Component   329

Activity 9.01: Creating an E-Commerce Application   335

Summary   337

10. Advanced Routing Techniques: Special Cases   339

Introduction   340

React Router Special Cases   340

Passing URL Parameters between Routes   340

Exercise 10.01: Creating URL Parameters   341

Matching Unknown Routes with 404 Pages   345

Exercise 10.02: Creating Unknown Routes   345

Rendering Nested Routes   348

Exercise 10.03: Creating Nested Routes   350

Protecting Routes   354

Preventing OutBound Transitions   354

Exercise 10.04: Protected Routes   355

Preventing Inbound Transitions   359

Activity 10.01: Creating Authentication Using Routing Techniques   360

Summary   363

11. Hooks – Reusability, Readability, and a Different Mental Model   365

Introduction   366

Hooks   366

useState   367

Exercise 11.01: Displaying an Image with the Toggle Button    368

useEffect – from Life Cycle Methods to Effect Hooks   372

Exercise 11.02: Creating a Login State Using useEffect   376

Comparing useEffect Hooks with Life Cycle Methods   382

Comparing Hooks to Render Props   384

Activity 11.01: Creating a Reusable Counter   386

Summary   387

12. State Management with Hooks   389

Introduction   390

useState Hook: A Closer Look   390

Setter Functions on Arrays   391

Exercise 12.01: Array Manipulation Using Hooks   392

Equality and Immutability for Objects in React   396

Limitations of useState   396

Using the useReducer Hook   396

Reducer Function in React   398

Exercise 12.02: useReducer with a Simple Form   400

Effects with Cleanup   407

Activity 12.01: Creating a Chat App Using Hooks   409

Summary   411

13. Composing Hooks to Solve Complex Problems   413

Introduction   414

Context API and Hooks   414

useContext Hook   415

Exercise 13.01: Adding Context to the ShoppingCart App   416

Props and Context   424

Props for Customization   425

Another Example: Theming as a Service   426

Exercise 13.02: Creating Context Using useContext and useEffect   428

Activity 13.01: Creating a Recipe App   434

Summary   436

14. Fetching Data by Making API Requests   439

Introduction   440

RESTful API    440

Five Common HTTP Methods   442

PUT versus PATCH 442

HTTP Status Codes   444

Accept Header and Content-Type Header   444

Different Ways of Requesting Data   447

XMLHttpRequest   448

Exercise 14.01: Requesting Data Using XMLHttpRequest   450

Fetch API   452

Exercise 14.02: Requesting Data Using the Fetch API   454

Axios   455

Exercise 14.03: Requesting Data Using Axios   457

Comparison of XMLHttpRequest, the Fetch API, and Axios   459

Axios versus the Fetch API   463

Better Response Handling 463

Better Error Handling 463

Testing APIs with Postman   465

Exercise 14.04: GET and POST Requests with Postman   467

Exercise 14.05: PUT, PATCH, and DELETE Requests with Postman   471

Making API Requests in React   473

React Boilerplate and Axios   473

Exercise 14.06: Installing React Boilerplate and Axios   474

Testing the NASA API with Postman   475

Exercise 14.07: Testing the Endpoint with Postman   476

Fetching Data with React   477

Exercise 14.08: Creating a Controlled Component to Fetch Data   477

Activity 14.01: Building an App to Request Data from Unsplash   483

Summary   485

15. Promise API and async/await   487

Introduction   488

What Is the Promise API?   488

Exercise 15.01: Fetching Data through Promises   491

What Is async/await?   499

async   500

await    500

then()   501

error()   501

finally()   502

Better Error Handling with async/await   502

Exercise 15.02: Converting submitForm() to async/await   504

async/await within Loops   508

for...of   509

forEach()   510

map()   510

Activity 15.01: Creating a Movie App   511

Summary   514

16. Fetching Data on Initial Render and Refactoring with Hooks   517

Introduction   518

Fetching Data upon Initial Rendering   518

Exercise 16.01: Fetching Popular Google Fonts on Initial Rendering   522

Fetching Data on Update   529

Infinite Loop   532

Exercise 16.02: Fetching Trending Google Fonts   533

React Hooks to Fetch Data   539

Exercise 16.03: Refactoring the FontList Component    541

More Refactoring with Custom Hook   545

Exercise 16.04: Refactoring a FontList Component with a Custom Hook   546

Activity 16.01: Creating an App Using Potter API   551

Summary   554

17. Refs in React   557

Introduction   558

Why React Refs?   558

References   558

Exercise 17.01: Creating Custom Upload Buttons with Refs   559

Ways of Creating React Refs   563

Exercise 17.02: Measuring the Dimensions of a div Element in a Class-Based Component   566

Exercise 17.03: Measuring the Element Size in a Functional Component   569

Forwarding Refs   571

Exercise 17.04: Measuring Button Dimensions Using a Forwarded Ref   575

Activity 17.01: Creating a Form with an Autofocus Input Element   579

Summary   581

18. Practical Use Cases of Refs   583

Introduction   584

Recap of React Refs Basics   584

Encapsulation via Props   586

DOM Manipulation Helpers   587

The cloneElement function in React   587

Exercise 18.01: Cloning an Element and Passing It an onClick Prop   589

The createPortal function in ReactDOM   592

Exercise 18.02: Creating a Global Overlay Using Portals   595

Activity 18.01: Portable Modals Using Refs   599

Summary   602

Appendix   605

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset