📄 Page
1
(This page has no text content)
📄 Page
2
(This page has no text content)
📄 Page
3
Stoyan Stefanov React: Up & Running Building Web Applications SECOND EDITION Boston Farnham Sebastopol TokyoBeijing
📄 Page
4
978-1-492-05146-6 [LSI] React: Up & Running by Stoyan Stefanov Copyright © 2022 Stoyan Stefanov. All rights reserved. Printed in the United States of America. Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472. O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles (https://oreilly.com). For more information, contact our corporate/institu‐ tional sales department: 800-998-9938 or corporate@oreilly.com. Acquisitions Editor: Jennifer Pollock Development Editor: Angela Rufino Production Editor: Kristen Brown Copyeditor: Justin Billing Proofreader: Piper Editorial Consulting, LLC Indexer: Sam Arnold-Boyd Interior Designer: David Futato Cover Designer: Karen Montgomery Illustrator: Kate Dullea July 2016: First Edition November 2021: Second Edition Revision History for the Second Edition 2021-11-11: First Release See https://oreilly.com/catalog/errata.csp?isbn=9781492051466 for release details. The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. React: Up & Running, the cover image, and related trade dress are trademarks of O’Reilly Media, Inc. While the publisher and the author have used good faith efforts to ensure that the information and instructions contained in this work are accurate, the publisher and the author disclaim all responsibility for errors or omissions, including without limitation responsibility for damages resulting from the use of or reliance on this work. Use of the information and instructions contained in this work is at your own risk. If any code samples or other technology this work contains or describes is subject to open source licenses or the intellectual property rights of others, it is your responsibility to ensure that your use thereof complies with such licenses and/or rights.
📄 Page
5
To Eva, Zlatina, and Nathalie
📄 Page
6
(This page has no text content)
📄 Page
7
Table of Contents Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xi 1. Hello World. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 Setup 1 Hello React World 2 What Just Happened? 3 React.createElement() 5 JSX 6 Setup Babel 7 Hello JSX World 8 On Transpilation 8 Next: Custom Components 9 2. The Life of a Component. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 A Custom Function Component 11 A JSX Version 12 A Custom Class Component 13 Which Syntax to Use? 13 Properties 14 Properties in Function Components 15 Default Properties 16 State 17 A textarea Component 18 Make It Stateful 19 A Note on DOM Events 21 Event Handling in the Olden Days 21 Event Handling in React 23 v
📄 Page
8
Event-Handling Syntax 23 Props Versus State 24 Props in Initial State: an Antipattern 25 Accessing the Component from the Outside 25 Lifecycle Methods 26 Lifecycle Example: Log It All 27 Paranoid State Protection 29 Lifecycle Example: Using a Child Component 30 Performance Win: Prevent Component Updates 33 Whatever Happened to Function Components? 34 3. Excel: A Fancy Table Component. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35 Data First 35 Table Headers Loop 36 Table Headers Loop, a Terse Version 37 Debugging the Console Warning 39 Adding <td> Content 40 Prop Types 42 Can You Improve the Component? 44 Sorting 44 Can You Improve the Component? 46 Sorting UI Cues 46 Editing Data 48 Editable Cell 49 Input Field Cell 51 Saving 51 Conclusion and Virtual DOM Diffs 52 Search 53 State and UI 54 Filtering Content 57 Update the save() Method 59 Can You Improve the Search? 59 Instant Replay 60 Cleaning Up Event Handlers 62 Cleaning Solution 63 Can You Improve the Replay? 64 An Alternative Implementation? 64 Download the Table Data 64 Fetching Data 66 vi | Table of Contents
📄 Page
9
4. Functional Excel. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69 A Quick Refresher: Function versus Class Components 69 Rendering the Data 70 The State Hook 71 Sorting the Table 73 Editing Data 75 Searching 76 Lifecycles in a World of Hooks 77 Troubles with Lifecycle Methods 77 useEffect() 78 Cleaning Up Side Effects 79 Trouble-Free Lifecycles 80 useLayoutEffect() 81 A Custom Hook 83 Wrapping up the Replay 85 useReducer 86 Reducer Functions 87 Actions 87 An Example Reducer 88 Unit Testing Reducers 90 Excel Component with a Reducer 91 5. JSX. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95 A Couple Tools 95 Whitespace in JSX 97 Comments in JSX 99 HTML Entities 100 Anti-XSS 101 Spread Attributes 101 Parent-to-Child Spread Attributes 102 Returning Multiple Nodes in JSX 104 A Wrapper 104 A Fragment 105 An Array 105 Differences Between JSX and HTML 106 No class, What for? 106 style Is an Object 107 Closing Tags 107 camelCase Attributes 108 Namespaced Components 108 JSX and Forms 109 Table of Contents | vii
📄 Page
10
onChange Handler 109 value Versus defaultValue 111 <textarea> Value 111 <select> Value 112 Controlled and Uncontrolled Components 113 6. Setting Up for App Development. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119 Create React App 119 Node.js 120 Hello CRA 120 Build and Deploy 122 Mistakes Were Made 123 package.json and node_modules 123 Poking Around the Code 124 Indices 124 JavaScript: Modernized 124 CSS 125 Moving On 126 7. Building the App’s Components. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127 Setup 127 Start Coding 127 Refactoring the Excel Component 129 Version 0.0.1 of the New App 130 CSS 131 Local Storage 132 The Components 133 Discovery 134 Logo and a Body 136 Logo 136 Body 136 Discoverable 136 <Button> Component 137 Button.js 138 classnames Package 139 Forms 140 <Suggest> 140 <Rating> Component 142 A <FormInput> “Factory” 144 <Form> 147 <Actions> 151 viii | Table of Contents
📄 Page
11
Dialogs 152 Header 157 App Config 157 <Excel>: New and Improved 159 The Overall Structure 161 Rendering 162 React.Strict and Reducers 166 Excel’s Little Helpers 168 8. The Finished App. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173 Updated App.js 176 DataFlow Component 176 DataFlow Body 178 Job Done 180 Whinepad v2 182 Context 182 Next Steps 183 Circular Data 184 Providing Context 184 Consuming Context 187 Context in the Header 187 Context in the Data Table 191 Updating Discovery 193 Routing 195 Route Context 195 Using the Filter URL 197 Consuming the Route Context in the Header 199 Consuming the Route Context in the Data Table 201 useCallback() 202 The End 204 Index. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205 Table of Contents | ix
📄 Page
12
(This page has no text content)
📄 Page
13
Preface It’s yet another wonderful warm California night. The faint ocean breeze only helping you feel 100% “aaah!” The place: Los Angeles; the year: 2000-something. I was just getting ready to FTP my new little web app called CSSsprites.com to my server and release it to the world. I contemplated a problem on the last few evenings I spent working on the app: why on earth did it take 20% effort to wrap up the “meat” of the app and then 80% to wrestle with the user interface? How many other tools could I have made if I didn’t have to getElementById() all the time and worry about the state of the app? (Is the user done uploading? What, an error? Is this dialog still on?) Why is UI development so time consuming? And what’s up with all the different browsers? Slowly, the “aaah” was turning into “aarrggh!” Fast forward to March 2015 at Facebook’s F8 conference. The team I’m part of is ready to announce a complete rewrite of two web apps: our third-party comments offering and a moderation tool to go with it. Compared to my little CSSsprites.com app, these were fully fledged web apps with tons more features, way more power, and insane amounts of traffic. Yet, the development was a joy. Teammates new to the app (and some even new to JavaScript and CSS) were able to come and contribute a fea‐ ture here and an improvement there, picking up speed quickly and effortlessly. As one member of the team said, “Ah-ha, now I see what all the love is all about!” What happened along the way? React. React is a library for building UIs—it helps you define the UI once and for all. Then, when the state of the app changes, the UI is rebuilt to react to the change and you don’t need to do anything extra. After all, you’ve defined the UI already. Defined? More like declared. You use small, manageable components to build a large, powerful app. No more spending half of your function’s body hunting for DOM nodes; all you do is maintain the state of your app (with a regular old JavaScript object) and the rest just follows. xi
📄 Page
14
Learning React is a sweet deal—you learn one library and use it to create all of the following: • Web apps • Native iOS and Android apps • TV apps • Native desktop apps You can create native apps with native performance and native controls (real native controls, not native-looking copies) using the same ideas of building components and UIs. It’s not about “write once, run everywhere” (our industry keeps failing at this); it’s about “learn once, use everywhere.” To cut a long story short: learn React, take 80% of your time back, and focus on the stuff that matters (like the real reason your app exists). About This Book This book focuses on learning React from a web development point of view. For the first three chapters, you start with nothing but a blank HTML file and keep building up from there. This allows you to focus on learning React and not any of the new syntax or auxiliary tools. Chapter 5 focuses more on JSX, which is a separate and optional technology that is usually used in conjunction with React. From there you learn about what it takes to develop a real-life app and the additional tools that can help you along the way. The book uses create-react-app to get off the ground quickly and keep discussion of auxiliary technologies to a minimum. The goal is to focus on React above all. A controversial decision was the inclusion of class components in addition to function components. Function components are likely the way forward; however, the reader is likely to encounter existing code and tutorials that talk only about class components. Knowing both syntaxes doubles the chances of reading and understanding code in the wild. Good luck on your journey toward learning React—may it be a smooth and fruitful one! xii | Preface
📄 Page
15
Conventions Used in This Book The following typographical conventions are used in this book: Italic Indicates new terms, URLs, email addresses, filenames, and file extensions. Constant width Used for program listings, as well as within paragraphs to refer to program ele‐ ments such as variable or function names, databases, data types, environment variables, statements, and keywords. Constant width bold Shows commands or other text that should be typed literally by the user. This element signifies a tip or suggestion. This element signifies a general note. Using Code Examples Supplemental material (code examples, exercises, etc.) is available for download at https://github.com/stoyan/reactbook2. If you have a technical question or a problem using the code examples, please send email to bookquestions@oreilly.com. This book is here to help you get your job done. In general, if example code is offered with this book, you may use it in your programs and documentation. You do not need to contact us for permission unless you’re reproducing a significant portion of the code. For example, writing a program that uses several chunks of code from this book does not require permission. Selling or distributing examples from O’Reilly books does require permission. Answering a question by citing this book and quoting example code does not require permission. Incorporating a significant amount of example code from this book into your product’s documentation does require permission. Preface | xiii
📄 Page
16
We appreciate, but do not require, attribution. An attribution usually includes the title, author, publisher, and ISBN. For example: “React: Up & Running, 2nd edition, by Stoyan Stefanov (O’Reilly). Copyright 2022 Stoyan Stefanov, 978-1-492-05146-6.” If you feel your use of code examples falls outside fair use or the permission given above, feel free to contact us at permissions@oreilly.com. O’Reilly Online Learning For more than 40 years, O’Reilly Media has provided technol‐ ogy and business training, knowledge, and insight to help companies succeed. Our unique network of experts and innovators share their knowledge and expertise through books, articles, and our online learning platform. O’Reilly’s online learning platform gives you on-demand access to live training courses, in-depth learning paths, interactive coding environments, and a vast collection of text and video from O’Reilly and 200+ other publishers. For more information, visit https://oreilly.com. How to Contact Us Please address comments and questions concerning this book to the publisher: O’Reilly Media, Inc. 1005 Gravenstein Highway North Sebastopol, CA 95472 800-998-9938 (in the United States or Canada) 707-829-0515 (international or local) 707-829-0104 (fax) We have a web page for this book, where we list errata, examples, and any additional information. You can access this page at https://oreil.ly/reactUR_2e. Email bookquestions@oreilly.com to comment or ask technical questions about this book. For news and information about our books and courses, visit https://oreilly.com. Find us on Facebook: https://facebook.com/oreilly Follow us on Twitter: https://twitter.com/oreillymedia Watch us on YouTube: https://www.youtube.com/oreillymedia xiv | Preface
📄 Page
17
Acknowledgments I’d like to thank to everyone who read different drafts of this book and sent feedback and corrections. For the first edition: Andreea Manole, Iliyan Peychev, Kostadin Ilov, Mark Dup‐ penthaler, Stephan Alber, and Asen Bozhilov. For the second edition: Adam Rackis, Maximiliano Firtman, Chetan Karande, Kiril Christov, and Scott Satoshi Iwako. Thanks to all the folks at Facebook who work on (or with) React and answer my questions day in and day out. Also to the extended React community that keeps pro‐ ducing great tools, libraries, articles, and usage patterns. Many thanks to Jordan Walke. Thanks to everyone at O’Reilly who made this book possible: Angela Rufino, Jennifer Pollock, Meg Foley, Kim Cofer, Justin Billing, Nicole Shelby, Kristen Brown, and many others. Thanks to Javor Vatchkov who designed the UI of the example app developed in this book (try it at whinepad.com). Preface | xv
📄 Page
18
(This page has no text content)
📄 Page
19
CHAPTER 1 Hello World Let’s get started on the journey to mastering application development using React. In this chapter, you will learn how to set up React and write your first “Hello World” web app. Setup First things first: you need to get a copy of the React library. There are various ways to go about it. Let’s go with the simplest one that doesn’t require any special tools and can get you learning and hacking away in no time. Create a folder for all the code in the book in a location where you’ll be able to find it. For example: $ mkdir ~/reactbook Create a /react folder to keep the React library code separate. $ mkdir ~/reactbook/react Next, you need to add two files: one is React itself, the other is the ReactDOM add- on. You can grab the latest 17.* versions of the two from the unpkg.com host, like so: $ curl -L https://unpkg.com/react@17/umd/react.development.js > ~/reactbook/ react/react.js $ curl -L https://unpkg.com/react-dom@17/umd/react-dom.development.js > ~/react- book/react/react-dom.js Note that React doesn’t impose any directory structure; you’re free to move to a dif‐ ferent directory or rename react.js however you see fit. 1
📄 Page
20
You don’t have to download the libraries; you can use them directly from unpkg.com. However, having them locally makes it possible to learn anywhere and without an internet connection. The @17 in the URLs shown in the preceding example gets you a copy of the latest React 17, which is current at the time of writing this book. Omit @17 to get the latest available React version. Alter‐ natively, you can explicitly specify the version you require, for example @17.0.2. Hello React World Let’s start with a simple page in your working directory (~/reactbook/ 01.01.hello.html): <!DOCTYPE html> <html> <head> <title>Hello React</title> <meta charset="utf-8"> </head> <body> <div id="app"> <!-- my app renders here --> </div> <script src="react/react.js"></script> <script src="react/react-dom.js"></script> <script> // my app's code </script> </body> </html> You can find all the code from this book in the accompanying repository. Only two notable things are happening in this file: • You include the React library and its Document Object Model (DOM) add-on (via <script src> tags) • You define where your application should be placed on the page (<div id="app">) 2 | Chapter 1: Hello World