Beginning ReactJS Foundations Building User Interfaces with ReactJS - Chris Minnick - E-Book

Beginning ReactJS Foundations Building User Interfaces with ReactJS E-Book

Chris Minnick

0,0
32,99 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.
Mehr erfahren.
Beschreibung

Quickly learn the most widely used front-end development language with ease and confidence

React JS Foundations: Building User Interfaces with ReactJS - An Approachable Guide walks readers through the fundamental concepts of programming with the explosively popular front-end tool known as React JS.

Written by an accomplished full-stack engineer, speaker, and community organizer, React JS Foundations teaches readers how to understand React and how to begin building applications with it. The book:

  • Explains and clarifies technical terminology with relevant and modern examples to assist people new to programming understand the language
  • Helps experienced programmers quickly get up to speed with React
  • Is stocked throughout with practical and applicable examples of day-to-day React work

Perfect for beginner, intermediate, and advanced programmers alike, React JS Foundations will quickly bring you up to speed on one of the most useful and widely used front-end languages on the web today. You can start building your first application today.

Sie lesen das E-Book in den Legimi-Apps auf:

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 596

Veröffentlichungsjahr: 2022

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Table of Contents

COVER

TITLE PAGE

INTRODUCTION

WHY THIS BOOK?

WHAT'S COVERED IN THIS BOOK?

WHAT'S NOT COVERED?

PREREQUISITES

INSTALLING REQUIRED DEPENDENCIES

READER SUPPORT FOR THIS BOOK

1 Hello, World!

REACT WITHOUT A BUILD TOOLCHAIN

INTERACTIVE “HELLO, WORLD” WITH CREATE REACT APP AND JSX

SUMMARY

2 The Foundation of React

WHAT'S IN A NAME?

UI LAYER

VIRTUAL DOM

THE PHILOSOPHY OF REACT

SUMMARY

3 JSX

JSX IS NOT HTML

WHAT IS JSX?

SYNTAX BASICS OF JSX

SUMMARY

4 All About Components

WHAT IS A COMPONENT?

COMPONENTS VS. ELEMENTS

BUILT-IN COMPONENTS

USER-DEFINED COMPONENTS

TYPES OF COMPONENTS

REACT COMPONENT CHILDREN

THE COMPONENT LIFECYCLE

RENDERING COMPONENTS

COMPONENT TERMINOLOGY

SUMMARY

5 React DevTools

INSTALLATION AND GETTING STARTED

INSPECTING COMPONENTS

EDITING COMPONENT DATA IN DEVTOOLS

WORKING WITH ADDITIONAL DEVTOOLS FUNCTIONALITY

PROFILING

SUMMARY

6 React Data Flow

ONE-WAY DATA FLOW

PROPS

REACT STATE

CONVERTING TO CLASS COMPONENTS

SUMMARY

7 Events

HOW EVENTS WORK IN REACT

WHAT IS SYNTHETICEVENT?

USING EVENT LISTENER ATTRIBUTES

THE EVENT OBJECT

SUPPORTED EVENTS

EVENT HANDLER FUNCTIONS

SUMMARY

8 Forms

FORMS HAVE STATE

CONTROLLED INPUTS VS. UNCONTROLLED INPUTS

LIFTING UP INPUT STATE

USING UNCONTROLLED INPUTS

USING DIFFERENT FORM ELEMENTS

PREVENTING DEFAULT ACTIONS

SUMMARY

9 Refs

WHAT REFS ARE

HOW TO CREATE A REF IN A CLASS COMPONENT

HOW TO CREATE A REF IN A FUNCTION COMPONENT

USING REFS

CREATING A CALLBACK REF

WHEN TO USE REFS

WHEN NOT TO USE REFS

EXAMPLES

SUMMARY

10 Styling React

THE IMPORTANCE OF STYLES

IMPORTING CSS INTO THE HTML FILE

USING PLAIN OLD CSS IN COMPONENTS

WRITING INLINE STYLES

CSS MODULES

CSS-IN-JS AND STYLED COMPONENTS

SUMMARY

11 Introducing Hooks

WHAT ARE HOOKS?

WHY WERE HOOKS INTRODUCED?

RULES OF HOOKS

THE BUILT-IN HOOKS

WRITING CUSTOM HOOKS

LABELING CUSTOM HOOKS WITH USEDEBUGVALUE

FINDING AND USING CUSTOM HOOKS

SUMMARY

12 Routing

WHAT IS ROUTING?

HOW ROUTING WORKS IN REACT

USING REACT ROUTER

REACT ROUTER HOOKS

SUMMARY

13 Error Boundaries

THE BEST LAID PLANS

WHAT IS AN ERROR BOUNDARY?

IMPLEMENTING AN ERROR BOUNDARY

WHAT CAN'T AN ERROR BOUNDARY CATCH?

SUMMARY

14 Deploying React

WHAT IS DEPLOYMENT?

BUILDING AN APP

HOW IS A DEPLOYED APP DIFFERENT?

DEVELOPMENT MODE VS. PRODUCTION

PUTTING IT ON THE WEB

SUMMARY

15 Initialize a React Project from Scratch

BUILDING YOUR OWN TOOLCHAIN

HOW WEBPACK WORKS

AUTOMATING YOUR BUILD PROCESS

STRUCTURING YOUR SOURCE DIRECTORY

SUMMARY

16 Fetching and Caching Data

ASYNCHRONOUS CODE: IT'S ALL ABOUT TIMING

JAVASCRIPT NEVER SLEEPS

WHERE TO RUN ASYNC CODE IN REACT

WAYS TO FETCH

GETTING DATA WITH FETCH

GETTING DATA WITH AXIOS

USING WEB STORAGE

SUMMARY

17 Context API

WHAT IS PROP DRILLING?

HOW CONTEXT API SOLVES THE PROBLEM

COMMON USE CASES FOR CONTEXT

WHEN NOT TO USE CONTEXT

COMPOSITION AS AN ALTERNATIVE TO CONTEXT

EXAMPLE APP: USER PREFERENCES

SUMMARY

18 React Portals

WHAT IS A PORTAL?

COMMON USE CASES

SUMMARY

19 Accessibility in React

WHY IS ACCESSIBILITY IMPORTANT?

ACCESSIBILITY BASICS

IMPLEMENTING ACCESSIBILITY IN REACT COMPONENTS

SUMMARY

20 Going Further

TESTING

SERVER-SIDE RENDERING

PEOPLE TO FOLLOW

USEFUL LINKS AND RESOURCES

SUMMARY

INDEX

COPYRIGHT

DEDICATION

ABOUT THE AUTHOR

ABOUT THE TECHNICAL EDITOR

ACKNOWLEDGMENTS

END USER LICENSE AGREEMENT

List of Tables

Chapter 4

TABLE 4-1: HTML Elements Supported by React

TABLE 4-2: Functions vs. Classes

Chapter 6

TABLE 6-1: Comparing props and state

Chapter 7

TABLE 7-1: Events Supported by React

Chapter 12

TABLE 12-1: Properties and Methods of history

List of Illustrations

Introduction

FIGURE I-1: VS Code

FIGURE I-2: Download VS Code

FIGURE I-3: The VS Code welcome screen

FIGURE I-4: The VS Code Command Palette

FIGURE I-5: Creating a new file using the Command Palette

FIGURE I-6: Using Emmet to save typing

FIGURE I-7: Client-side React and server-side Node

FIGURE I-8: Development, client-side, and server-side

FIGURE I-9: Minification

FIGURE I-10: Transpiling example

FIGURE I-11: Module bundling

FIGURE I-12: The VS Code Terminal

FIGURE I-13: Checking that npm is installed

FIGURE I-14: Chrome DevTools

FIGURE I-15: React Developer Tools Components view

FIGURE I-16: The default Create React App boilerplate

Chapter 1

FIGURE 1-1: The React CDN Links

FIGURE 1-2: Hello, World running in a browser

FIGURE 1-3: The finished interactive Hello, World component!

Chapter 2

FIGURE 2-1: The MVC pattern

FIGURE 2-2: React and ReactDOM

FIGURE 2-3: How the Virtual DOM works

FIGURE 2-4: How the web works

Chapter 3

FIGURE 3-1: Trying out Babel on the web

Chapter 4

FIGURE 4-1: A tree of react components

FIGURE 4-2: Using state immediately after calling setState() may produce une...

FIGURE 4-3: The result of rendering FigureList

FIGURE 4-4: Rendering the ThingsILike component

FIGURE 4-5: The component lifecycle

FIGURE 4-6: Incrementing a counter

FIGURE 4-7: The result of attempting to call setState on an unmounted compon...

FIGURE 4-8: Hello, React Native

Chapter 5

FIGURE 5-1: The React Bookstore sample app

FIGURE 5-2: The Chrome Developer Tools with React DevTools installed

FIGURE 5-3: The React DevTools Components tab

FIGURE 5-4: The component tree with ProductList collapsed

FIGURE 5-5: Creating new CartItem children

FIGURE 5-6: Searching for components containing “c”

FIGURE 5-7: Searching for components starting with “c”

FIGURE 5-8: React DevTools' View Settings

FIGURE 5-9: The component tree view with the default filter disabled

FIGURE 5-10: The React DevTools Select tool

FIGURE 5-11: Viewing component details

FIGURE 5-12: Attempting to add an out-of-range ID to the cart

FIGURE 5-13: Logging component data to the console

FIGURE 5-14: The Flamegraph chart

FIGURE 5-15: Viewing the Ranked chart

FIGURE 5-16: Ranked chart after optimizing

Chapter 6

FIGURE 6-1: Unidirectional data flow

FIGURE 6-2: Bidirectional data flow

FIGURE 6-3: Data flowing in one direction

FIGURE 6-4: Changing local variables doesn't update the view

FIGURE 6-5: Local variable and props confusion

FIGURE 6-6: Passing the wrong prop type

FIGURE 6-7: PropTypes displaying a warning

FIGURE 6-8: The not-renderable error message

FIGURE 6-9: PropTypes tell which attribute caused the error

FIGURE 6-10: Failing PropTypes.element validation

FIGURE 6-11: A custom PropType validator failing

FIGURE 6-12: The result of clicking the CounterClass button

FIGURE 6-13: The fixed counter class

FIGURE 6-14: A reminders app

FIGURE 6-15: The first round static version

FIGURE 6-16: A static version of the Reminders app

FIGURE 6-17: Cannot read property

FIGURE 6-18: Cannot read property ‘map' of undefined

FIGURE 6-19: Displaying the default prop

FIGURE 6-20: The initial render of the Reminders app

FIGURE 6-21: Adding Reminders to the list

FIGURE 6-22: Checking and unchecking isComplete checkboxes

Chapter 7

FIGURE 7-1: Viewing the properties of a SyntheticEvent

FIGURE 7-2: The NativeEvent properties

Chapter 8

FIGURE 8-1: Controlled and uncontrolled inputs

FIGURE 8-2: Rendering an uncontrolled input

FIGURE 8-3: Form input often affects other components

Chapter 9

FIGURE 9-1: The TextReader component

FIGURE 9-2: Selecting text and displaying a temporary message

Chapter 10

FIGURE 10-1: Cascading styles from parent to child

Chapter 11

FIGURE 11-1: Wrapper hell

FIGURE 11-2: Passing a setter function as a prop

FIGURE 11-3: Starting a new timer with each render

FIGURE 11-4: Running an effect only after mounting

FIGURE 11-5: Performing an asynchronous request using useEffect

FIGURE 11-6: Unnecessary renders warning due to a function dependency

FIGURE 11-7: Testing referential equality

FIGURE 11-8: Inspecting a custom hook

FIGURE 11-9: Viewing a Custom Hook's debug value

Chapter 12

FIGURE 12-1: How the web works

FIGURE 12-2: JavaScript routing

FIGURE 12-3: Changing routes and viewing the window.location.href property

FIGURE 12-4: React Router can't be used for external linking

FIGURE 12-5: Navigation links indicate the current position

FIGURE 12-6: A navigation menu with sub-items

FIGURE 12-7: Partial matches activate the active style

FIGURE 12-8: Using the exact attribute on NavLink components

FIGURE 12-9: Multiple routes can match the URL

FIGURE 12-10: Add the exact attribute to Routes to restrict matching

FIGURE 12-11: Modifying the current location

FIGURE 12-12: Dynamic link and path attributes with the match object propert...

Chapter 13

FIGURE 13-1: A crashed React app

FIGURE 13-2: A diagram of a typical UI

FIGURE 13-3: An uncaught error

FIGURE 13-4: Handling an error with an error boundary

FIGURE 13-5: Rendering a fallback UI

FIGURE 13-6: Viewing the error and info parameters in the console

FIGURE 13-7: Add a log source

FIGURE 13-8: The Customer Token link in Loggly

FIGURE 13-9: Viewing caught errors in Loggly

FIGURE 13-10: Providing a reset option in the error boundary

Chapter 14

FIGURE 14-1: The build directory

FIGURE 14-2: The minified and compiled index.html

FIGURE 14-3: Running a built app from the filesystem

FIGURE 14-4: Development vs. production in the Developer Tools

FIGURE 14-5: Click the New site from Git button

FIGURE 14-6: Choose your Git provider

FIGURE 14-7: Choose a repository

FIGURE 14-8: A deployed React app

FIGURE 14-9: Domain management in Netlify

Chapter 15

FIGURE 15-1: Attempting to load index.js without compiling

FIGURE 15-2: JSX requires a loader

FIGURE 15-3: The working React app

FIGURE 15-4: Starting the configuration wizard

FIGURE 15-5: Automatically fixable errors or warnings

FIGURE 15-6: No tests found

FIGURE 15-7: Test passed

FIGURE 15-8: Grouping by file type

FIGURE 15-9: Grouping by features

Chapter 16

FIGURE 16-1: Executing asynchronous JavaScript

FIGURE 16-2: How asynchronous tasks are handled

FIGURE 16-3: Remembering a user with Web Storage

FIGURE 16-4: Viewing Local Storage in Chrome Developer Tools

Chapter 17

FIGURE 17-1: Using a component outside of its Context

FIGURE 17-2: A user preferences component with Context

Chapter 18

FIGURE 18-1: Portals enable modal dialogs

FIGURE 18-2: Rendering the SalesChart component

FIGURE 18-3: Inspecting an app with a Portal in Chrome Developer Tools

FIGURE 18-4: Inspecting an app with a Portal in React Developer Tools

FIGURE 18-5: Rendering a modal without using React Portals can have unexpect...

FIGURE 18-6: The opened modal

FIGURE 18-7: A checkout form with help links

Chapter 20

FIGURE 20-1: The Flux pattern

FIGURE 20-2: Data flow in a Redux application

Guide

Cover

Table of Contents

Title Page

Copyright

Dedication

About the Author

About the Technical Editor

Acknowledgments

Introduction

Begin Reading

Index

End User License Agreement

Pages

iii

xxvii

xxviii

xxix

xxx

xxxi

xxxii

xxxiii

xxxiv

xxxv

xxxvi

xxxvii

xxxviii

xxxix

xl

xli

xlii

xliii

xliv

xlv

xlvi

xlvii

xlviii

xlix

l

li

lii

1

2

3

4

5

6

7

8

9

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

211

212

213

214

215

216

217

218

219

221

222

223

224

225

226

227

228

229

230

231

232

233

234

235

236

237

238

239

240

241

242

243

244

245

246

247

248

249

250

251

252

253

254

255

257

258

259

260

261

262

263

264

265

266

267

268

269

270

271

272

273

274

275

276

277

278

279

280

281

282

283

284

285

286

287

288

289

290

291

292

293

294

295

296

297

298

299

300

301

302

303

304

305

306

307

308

309

310

311

312

313

314

315

316

317

318

319

320

321

322

323

324

325

326

327

328

329

330

331

332

333

334

335

336

337

338

339

340

341

342

343

344

345

346

347

348

349

350

351

352

353

354

355

356

357

358

359

360

361

362

363

364

365

366

367

369

370

371

372

373

374

375

376

377

378

379

380

381

382

383

384

385

387

388

389

390

391

392

393

394

395

396

397

398

399

400

401

402

403

404

405

406

407

408

409

410

411

413

414

415

416

417

418

419

420

421

422

423

425

426

427

428

429

430

431

432

433

434

435

436

437

438

439

440

441

442

443

444

445

446

447

448

449

450

451

452

453

iv

v

vii

ix

xi

454

BEGINNINGReactJS FoundationsBuilding User Interfaces with ReactJS

AN APPROACHABLE GUIDE

 

Chris Minnick

 

 

 

 

 

INTRODUCTION

SINCE ITS CREATION BY FACEBOOK IN 2013, REACTJS  has become one of the most popular and widely used front-end user interface libraries on the web. With the creation of React Native in 2015, ReactJS has become one of the most widely used libraries for mobile app development as well.

ReactJS has always been a bit of a moving target. It has gone through several major changes over the years, but through it all, the core principles of React have remained the same.

If you want to learn to develop next-generation cross-platform web and mobile apps using the latest syntax and the latest tools, you've come to the right place. My goal with this book is to save you from the countless hours of trial and error that were my experience with trying to piece together bits of old and new information from the web and books.

Whether you're coming to React as a mobile developer, a web developer, or as any other kind of software developer, this book is for you. If you have experience with ReactJS as it existed in the earlier days (before about version 16), this book is for you too!

In this book, I've attempted not only to give the most up-to-date syntax and patterns for developing ReactJS applications, but also to give enough background and timeless information for it to remain relevant for years to come.

So, welcome to ReactJS.

WHY THIS BOOK?

Thank you for choosing to begin, or continue, your React journey with me. My aim with this book is to provide an up-to-date and thorough explanation of React and the React ecosystem along with hands-on code that will prepare you to quickly start using React productively in the real world.

I'm thrilled to be writing this book at this time for a number of reasons:

I have the experience and knowledge to do it right.

React is one of the most popular JavaScript libraries today.

I believe React will be even more popular in the future.

Existing online resources and books too often give incomplete and/or outdated information about how to program with React.

Let's take a quick look at each of these points, starting with a little bit about who I am and how I came to React and this book.

About Me

I've been a web developer since 1997, and I've been programming in JavaScript since 1998. I've built or managed the building of web applications for some of the world's largest companies over the years. As a web developer, writer, and teacher, I've had to learn and use plenty of languages and JavaScript frameworks. There's a difference between learning something and applying it, and I've been working on projects with React and doing React consulting for several years now.

I've been teaching web development and JavaScript online and in person since 2000, and I've been teaching React since 2015. In the years that I've been teaching React, I've written three weeklong courses designed for in-person delivery, numerous short video courses, and two longer video courses. I've taught React on three continents, and my students have been web developers, Java and C programmers, COBOL programmers, database administrators, network administrators, project managers, graphic designers, and college students.

As I'm writing, the global COVID-19 pandemic has decimated the in-person training industry. While this situation has given me more time at home with the pets, it's also given me time to think deeply about React and about the React book that I wish existed today. This book is the result of my looking at all of the top React books, looking at the current state of how React is being used, and looking at what React is likely to look like in the future.

React Is Popular

React is a JavaScript library that was born out of Facebook's need to create scalable and fast user interfaces. Ever since Facebook released it to the world as an open source project, it has been one of the most widely used ways to build dynamic web and mobile applications.

One popular game among JavaScript developers is to think of a noun, add “.js”, and search GitHub to find the JavaScript framework with that name. In a time when new JavaScript frameworks and libraries pop up and die off with shocking regularity, React is one of three libraries released since 2010 that have stuck around and gained the kind of developer usage that will guarantee that they will be supported and in widespread use for a long time to come.

React Is Both Progressive and Conservative

React has been able to stick around so long and gain so many users because it's always been a forward-looking framework that's not afraid to make big changes to adapt to new features in JavaScript, new ways of writing user interfaces, and feedback from developers. Over the years, React has gone through several major changes in how the basic unit of a React application, the component, is written. But, amidst all this change, React has stuck to a central paradigm and each major change to React has maintained compatibility with previous versions.

Don't Believe Everything on the Internet

While the end result of all this change is that React has gotten easier to write and more robust over the years, it's also caused a pileup of outdated and often wrong example code and tutorials on the internet and in books. If you've done any research on React prior to buying this book, you've surely noticed this, and you've likely been confused by it. Perhaps you bought this book after having a frustrating experience with learning React online only to learn that you learned about an old version of it.

This book aims to be a solid and complete guide to all of the most important (and some less important) features, concepts, and syntaxes used in React.

WHAT'S COVERED IN THIS BOOK?

This book covers everything you need to know to write high-quality React code. You'll learn about React components using the functional method of writing them as well as the class method. You'll learn about managing the state of your application using several different methods, including with React Hooks and with the setState method. You'll learn how to put components together to make complete and dynamic user interfaces. You'll learn how to fetch data from an external data source and use it in your application. And, you'll learn how to store data in the user's web browser to improve the performance and usability of your application. Speaking of usability, you'll learn about best practices for making your application work on mobile devices as well as on the desktop, and you'll also learn how to make sure that your application will be accessible.

Because React takes advantage of many of the latest and greatest improvements and enhancements to the underlying JavaScript language, I'll be giving you JavaScript lessons throughout the book. Some of the new JavaScript syntax can be a little confusing to those of us who first learned the language in its early days, but I'll provide plenty of simple and real-world examples to explain each new bit of syntax or shortcut.

WHAT'S NOT COVERED?

Although React is a JavaScript library, this is not a book for newcomers to JavaScript or to web programming. I expect that you've had at least some experience with JavaScript. If you're not familiar with the latest additions and revisions to JavaScript, that's not a problem. But, if you're new to JavaScript or to programming in general, I recommend that you learn the basics of programming with JavaScript before you tackle React.

Similarly, this is not a web design book. I assume that you're familiar with HTML and CSS and feel comfortable writing both. I also assume a basic knowledge of how web browsers work and how web pages are rendered in browsers.

Finally, this book is intended to teach the fundamentals of React to anyone who wants to gain the ability to write React applications. Although it does cover many of the most commonly used patterns and conventions in React development, and many of the more advanced topics in React are covered as well, there are many topics that will only be mentioned in passing or that had to be omitted for the sake of space. To cover everything having to do with more advanced React development would require several volumes, which would all need to be updated every couple of months.

Once you understand the fundamentals of React as taught in this book, you'll be more than qualified to explore the vast React online ecosystem and find tutorials, documentation, and example code to continue your React education.

Some of the more advanced topics that are beyond the scope of this book are: unit testing, building mobile applications with React Native, Redux, and isomorphic/universal React. If all that sounds like a bunch of nonsense jargon at this point, you came to the right place! You may not know everything about how to implement all these more advanced things by the end of the book, but you'll certainly know what they are and how to get started with them.

PREREQUISITES

Programming React can feel like assembling a complex piece of furniture from a Swedish furnishing store. There are a lot of parts that don't make much sense individually, but when you follow the instructions and put them together in the right way, the simplicity and beauty of the whole thing may surprise you.

Internet Connection and Computer

I assume that you have a connection to the internet and a reasonably modern desktop or laptop computer. Writing code on tablets or smartphones is possible, but it's not easy. My examples and screenshots will be from the perspective of a desktop and/or laptop computer, and I can't guarantee that my example code will all be usable on a smaller device. Furthermore, some of the tools that you'll be using to build React applications simply won't run on a smartphone or tablet.

Web Development Basics

As previously mentioned, an understanding of HTML, CSS, and JavaScript is essential before beginning your study of React. If your experience is mostly with copying and pasting code that others have written, but you feel comfortable with making changes and looking up things that you don't yet know, you'll do fine with this book.

Code Editor

You'll need a code editor. The one I currently use and recommend is Microsoft Visual Studio Code. It's available for free on MacOS, Linux, and Windows. If you're more comfortable using another code editor, that's fine too. I've used many different code editors over the years, and I believe that whichever code editor a developer chooses to use and can be most effective with is the right one.

Browser

You'll also need a modern web browser. Although Mozilla Firefox, Google Chrome, and Windows Edge will all work for our purposes, my screenshots throughout the book were taken in Google Chrome on MacOS. Feel free to use whichever of the three modern web browsers you prefer, but understand that your experience may differ slightly from the screenshots in the book and that some of the React developer tools are currently only available for Chrome and Firefox.

INSTALLING REQUIRED DEPENDENCIES

Although it is possible to write and run React applications with nothing more than a text editor and a web browser on a computer connected to the internet, if you want to build any applications that will be deployed to the public web you'll need to install some additional software packages on your computer. These packages, when combined, are what web developers refer to as a toolchain.

All of the tools in the React toolchain are free, open source, and easy to download and install. In the following pages, I'll take you step by step through installing and configuring your toolchain and I'll show you some of the things you'll be able to do with your new tools to help you efficiently build, compile, and deploy React applications in a modern, standard, and professional way.

Introducing Visual Studio Code

In my more than 25 years as a web developer, I've used many different code editors, and I still switch code editors from time to time depending on the project or the type of code I'm writing.

However, there always seems to be a “popular” code editor that the majority of web developers use. Which editor is the popular one has changed several times over the years, but as of this writing, the code editor that seems to be most widely used for writing front-end web code is Microsoft's Visual Studio Code (aka VS Code), shown in Figure I-1.

FIGURE I-1: VS Code

Visual Studio Code is free and open source, and it's available for Windows, Linux, and MacOS. It features built-in support for React development and many plugins have been developed for it that can be helpful for writing and debugging React projects.

For these reasons, I'll be using the latest version of Visual Studio Code in this book, and my screenshots and step-by-step instructions may be specific to Visual Studio Code in some places. If you choose to use a different code editor, be aware that you'll need to translate a few specific instructions to your environment.

If you don't already have Visual Studio Code installed, follow these steps to get it:

Open

code.visualstudio.com

in your web browser and click the download link for your operating system (

Figure I-2

).

FIGURE I-2: Download VS Code

Double-click the downloaded file to start the installation process.

Accept the default options if you're presented with any options during installation.

Once you have Visual Studio Code, launch it. If this is the first time you've used it, you'll see the welcome screen, as shown in Figure I-3.

FIGURE I-3: The VS Code welcome screen

If you'd like to open the welcome screen at any point, you can do so by selecting Get Started from the Help menu.

The first and most important thing to learn about VS Code is how to use the Command Palette. The Command Palette gives you quick access to all of VS Code's commands. Follow these steps to become familiar with the Command Palette:

Open the Command Palette by selecting it from the View menu, or by pressing Command+Shift+P (on MacOS) or CTRL+Shift+P (on Windows). An input box will appear at the top of the VS Code interface, as shown in

Figure I-4

.

NOTE Since you're likely going to be using the Command Palette regularly, take a moment to memorize that keyboard shortcut.

FIGURE I-4: The VS Code Command Palette

Type

new file

into the Command Palette input field. As you type, you'll see a list of available commands below your input.

When you see

File: New Untitled File

at the top of the Command Palette (as shown in

Figure I-5

), press Enter. A new untitled file will be created.

FIGURE I-5: Creating a new file using the Command Palette

Open the Command Palette again and start typing

save

. When File: Save is highlighted, press Enter to save your file. Give it a name ending with

.html

(such as

index.html

).

Type

!

on the first line of your new file and then press the Tab key. The scaffolding for a new HTML file will be written for you, which will look like

Figure I-6

. This magical code-generating feature is called Emmet. Emmet can be used to automate many routine tasks and speed the writing of code, and it would be a great idea to start getting familiar with it and practicing the use of it right away.

Use

CTRL+s

or the Command Palette to save your new file.

FIGURE I-6: Using Emmet to save typing

Node.js

Node.js started as a way to run JavaScript on web servers. The benefits of doing this are that, using Node.js (also known as just “Node”), programmers can use the same language on the client side (in the web browser) as they use on the web server (aka “server side”). Not only does this reduce the number of programming languages that a programmer or a team of programmers needs to be fluent in, but Node.js also makes communication between the server and web browsers easier because both are speaking the same language.

Figure I-7 shows a basic web application with Node.js running on the server and JavaScript running in a web browser.

FIGURE I-7: Client-side React and server-side Node

As Node.js became popular, people also started to run it on their own computers as a way to run JavaScript programs outside of web browsers. Specifically, web developers used Node.js to run tools for automating many of the complex tasks involved in modern web development, as shown in Figure I-8.

FIGURE I-8: Development, client-side, and server-side

Common tasks that take place in development and that can be aided by Node.js include:

Minification:

The process of removing spaces, line breaks, comments, and other code that's not required for the program to run, but that is helpful for people who work on the program. Minification makes scripts, web pages, and stylesheets more efficient and faster.

Figure I-9

shows the difference between JavaScript code as it's written by a programmer and minified code.

FIGURE I-9: Minification

Transpiling:

The process of converting programming code from one version of a programming language into another version. This is necessary in web development because not all web browsers support the same set of new JavaScript features, but they do all support some core subset of JavaScript features. By using a JavaScript transpiler, programmers can write code using the latest version of JavaScript and then the transpiled code can be run in any web browser.

Figure I-10

shows an example use of JavaScript template strings, which were introduced in ES2015, along with their equivalent in an earlier version of JavaScript.

FIGURE I-10: Transpiling example

Module bundling:

A typical website can make use of hundreds of individual JavaScript programs. If a web browser had to download each of these different programs individually, it would significantly slow down web pages due to the overhead involved with requesting files from web servers. The main job of a module bundler is to combine (or “bundle”) the JavaScript and other code involved in a web application to make serving the application faster. Because a bundler has to do work to all of the files in a program, it also is a good central place for tasks like minification and transpiling to take place, through the use of plugins.

Figure I-11

illustrates the process of module bundling.

FIGURE I-11: Module bundling

Package management:

With so many different programs involved in JavaScript development, just installing, upgrading, and keeping track of them can be quite complex. A package manager is a program that helps you with tasks related to the management of all these programs (which are also known as “packages” in Node.js lingo).

CSS preprocessor:

A CSS preprocessor, such as SASS or LESS, allows you to write style sheets for your web application using a superset of CSS (such as SCSS) that supports the programmatic features that CSS lacks—things like variables, mathematic operations, functions, scope, and nesting. A CSS preprocessor produces standard CSS from code written using an alternative syntax.

Testing frameworks:

Testing is an essential part of any web project. Properly written tests can tell you whether each piece of your application is working as it was designed. The process of writing logic to test whether your application works as it should is also a powerful tool for helping you to write better code.

Build automation:

If you had to run each of the different tools involved in compiling a modern web app every time you wanted to test it out and deploy it to the web, you would have a very complex series of steps to follow and use to train anyone else who might work on the code. Build automation is the process of writing a program or script that runs all of the different tools for you in the right order to quickly and reliably optimize, compile, test, and deploy applications.

These are just a few of the different types of tools that are written in JavaScript and run in Node.js that front-end developers use on a regular basis. If you'd like to explore the vast universe of Node.js packages, visit the npm Package Repository at https://npmjs.com, or continue to the next section to learn about managing and installing Node.js packages.

Getting Started with Node.js

The most common way of interacting with Node.js is through commands typed into a UNIX-style terminal. You can access a terminal from within Visual Studio Code using three different methods:

By selecting

New Terminal

from the Terminal menu.

By right-clicking a folder in VS Code's file explorer and selecting

Open in Integrated Terminal

.

By using the keyboard shortcut

CTRL+~

.

Whichever way you choose (and I recommend getting comfortable with the keyboard shortcut to save yourself from having to switch to using your mouse), a window will open at the bottom of VS Code that looks like Figure I-12.

FIGURE I-12: The VS Code Terminal

The first step in learning to use Node.js is to make sure that it's installed on your computer. If you have a computer running MacOS or Linux, chances are good that it's already installed, but you may need to upgrade to a newer version. On Windows, it may not be installed, but that's easy to fix. Follow these steps to check whether you have Node.js installed, see what version is installed, and upgrade to the latest version:

Open the Terminal in Visual Studio Code.

In the Terminal, type

node -v

. If Node.js is installed, it will return a version number. If the version number is lower than 14.0, you'll need to upgrade. Proceed to step 4. If your version of Node.js is greater than 14.0, you may still want to proceed to step 4 and upgrade to the latest version of Node.js, but it's not required.

If Node.js is not installed, you'll get a message that

node

is an unknown command. Proceed to step 4.

Go to

https://nodejs.org

in your web browser and click the link to download the current LTS version of Node.js.

When the Node.js installer finishes downloading, double-click it and follow the instructions to install it.

If you have a Terminal window open in Visual Studio Code, close it and then re-open it.

Type

node -v

into your Terminal. You should now see that you have the latest version of Node.js installed.

Node.js Package Management with yarn or npm

Now that you have Node.js installed, the next step is to learn to use a package manager to install and upgrade Node.js packages. When you installed Node.js, you also installed a package manager called npm. This is the package manager that we'll be using in this book, because it's the most commonly used one, and because you already have it. There are other package managers, however. One of them, which has become quite widely used, for a number of reasons that we don't have the space to go into here, is called yarn. The commands that you use for npm and yarn are actually quite similar. If you'd like to find out more about yarn, and why you might want to use it, you can do so by visiting www.yarnpkg.com.

If you have Node.js installed, you already have npm installed. You can verify this by following these steps:

Open the Terminal in Visual Studio Code.

Type

npm -v

at the command line. You should get a response similar to the one shown in

Figure I-13

.

FIGURE I-13: Checking that npm is installed

If you have an older version of npm installed, it can cause some of the commands we'll run in this Introduction and the book's chapters to not work correctly. If you use MacOS, you can upgrade npm by entering the following command in the Terminal:

sudo npm install -g npm

After you type this command in the Terminal and press Enter, you'll be asked for a password. This is the password that you use to log in to your computer.

If you use Windows, you can upgrade npm by entering the following command:

npm install -g npm

Note that you must have administrative access to your computer to run this command.

The npm install command is how you can download and install Node.js packages to your computer so you can run them or so other programs can make use of them. When a computer program needs another computer program in order to run, we call the program it requires a dependency. Because Node.js programs are made up of small packages that often individually have reusable and limited functionality, it's not uncommon for a Node.js package to have hundreds of dependencies.

When you run npm install followed by the name of a Node.js package, npm looks for that package in the npm repository, downloads it (along with all of its dependencies), and installs it. Packages may be installed globally, which makes them available to any program on your computer, by specifying the -g flag after the npm install command. So, when we say npm install-g npm, what happens is that the npm package installs the latest version of itself. In other words, it upgrades.

In addition to being able to install packages globally, npm can also install packages locally, which makes them available only to the current project.

NOTE Whenever possible, it's a good practice to only install packages locally in order to reduce the potential for version conflicts and to make your programs more reusable and more easily shared.

Follow these instructions to see the npm install command in action:

Open Visual Studio Code and click the File Explorer icon on the left toolbar.

Click

Open Folder

and use the file browser that it opens to create a new folder named

chapter-0

in your computer's Documents folder and open that folder.

Open the integrated Terminal application in Visual Studio Code. It will open a command-line interface and set the current directory to the folder that you have open.

Type npm init -y. Running

npm init

creates a new file called

package.json

, whose purpose is to track dependencies and other meta information about your node package.

Type npm install learnyounode -g, or sudo npm install learnyounode -g (on MacOS or Linux). This will install an npm package created by NodeSchool (

nodeschool.io

) that teaches you how to use Node.js. As the

learnyounode

package is downloaded and installed, you'll see some messages fly by on the screen (and possibly a few warnings or errors—these are normal and nothing to worry about).

When the package has finishing installing, type learnyounode in the Terminal to run it. Your command prompt will be replaced by a menu of lessons. I recommend going through at least the first one or two of these lessons at your convenience so that you can get a better idea of what Node.js is, although a deep understanding isn't necessary for learning React.

NOTE You may get an error message saying that running scripts is disabled when you try to run thenpm installcommand on Windows. If you do, entering the following command into the Terminal should solve the problem:

Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass

Chrome DevTools

Google's Chrome browser includes a powerful set of tools for inspecting and debugging websites and web applications. Follow these steps to get started with using Chrome DevTools:

Open your Chrome browser and go to

www.example.com

. You'll see a simple example web page. The simplicity of this page makes it a great place to start to learn about Chrome DevTools.

Open the Chrome DevTools panel by clicking the three dots in the upper-right corner of Chrome (this is known as the Chrome Menu) and selecting

More Tools

Developer Tools

or by using the keyboard shortcut:

Command+Option+I

(on MacOS)

or CTRL+Shift+I

(on Windows). The keyboard shortcut is not only easier, it is also unlikely to ever change, whereas the location of the Developer Tools menu item has changed several times over the years. Either way you open it, a panel will open up in your browser, containing the DevTools, as shown in

Figure I-14

.

NOTE The default docking position for Chrome DevTools is on the right side of the browser window. You can change where the tools are docked by clicking the three dots (known as a “kebab” menu icon) in the upper-right corner of the DevTools pane.

FIGURE I-14: Chrome DevTools

Look for the element selector tool in the upper-left corner of the DevTools panel and click it. You can use the element selector tool to inspect the different HTML elements in a web page.

Use the element selector tool to highlight different parts of the

www.example.com

web page. When you have the header of the page highlighted, click it. The HTML that creates the header will be highlighted in the source code view in DevTools, and the CSS styles that are applied to the header will be shown to the right of the source code.

Double-click the words Example Domain inside the

<h1>

element in the source code view. The words will become highlighted and editable.

With the words Example Domain highlighted in the source code view, type new words over them to replace them and then press Enter to exit the source editing mode. Your new text will appear in the browser window as the

<h1>

element.

Find the

<h1>

element style in the styles pane to the right of the source code window and double-click it.

Try changing the styles that are applied to the

<h1>

element and notice that they modify what's showing in the browser window.

Click the

Console

tab at the top of the DevTools pane. This will open the JavaScript console.

Type the following JavaScript into the JavaScript console:

document.getElementsByTagName('h1')[0].innerText

When you press Enter, the text between the opening and closing <h1> tags will be logged to the console.

The important thing to know about everything we've done with the Chrome DevTools so far, and the first key to understanding how React works, is that you're not actually changing the HTML web page itself. That is safely stored on a web server. What you're changing is your web browser's in-memory representation of the web page. If you refresh the page, it will be re-downloaded and will appear as it did when you first loaded it.

The method that DevTools uses to manipulate the web page is through the Document Object Model, or DOM. The DOM is the JavaScript application programming interface (API) for web pages. By manipulating the DOM, you can dynamically alter anything in a web browser window. DOM manipulation is the way that JavaScript frameworks and libraries, including React, make web pages more interactive and more like native desktop applications.

React Developer Tools

To help developers debug React applications, Facebook created a browser extension called React Developer Tools. React Developer Tools is currently only available for Chrome and Firefox. Once installed, React Developer Tools gives you two new buttons in the browser developer tools: Components and Profiler.

Let's first look at how to install React Developer Tools and then we'll look at what it does.

Follow these steps to install React Developer Tools in Chrome:

Go to the Chrome Web Store at

https://chrome.google.com/webstore

using your Chrome browser.

Enter

React Developer Tools

into the search box. The first result will be the React Developer Tools extension by Facebook.

Click the React Developer Tools extension and then click the

Add to Chrome

button. The extension will be installed in your browser.

Here's how to install the React Developer Tools AddOn in Firefox:

Open your Firefox browser and go to

https://addons.mozilla.org/en-US/firefox/addon/react-devtools/

.

Click the

Add to Firefox

button.

When Firefox asks you for permission to install the AddOn, click

Add

.

Once it's installed, follow these steps to get started with using the React Developer Tools:

Open the Chrome DevTools or the Firefox Developer Tools.

Notice that if you're not currently viewing a web page that uses React, you won't see any difference in the Developer Tools.

Go to

https://reactjs.org

in your browser. In the Developer Tools, you'll see new tabs for Components and Profiler appear.

Click the Components tab. You'll see a tree view of the React user interface, as shown in

Figure I-15

.

FIGURE I-15: React Developer Tools Components view

Each of the items in the React Components view is a different component in the React application. On most public websites that use React, the component names that display in the React Developer Tools won't make much sense, and the React Developer Tools are only of limited functionality. This is because there are actually separate versions of React for development (which is when you're building and debugging the application) and for production (which is when the application is deployed and available to end users).

The production version of React uses minified component names, and most of the debugging functionality is removed in order to increase performance and decrease the size of the download required for the browser to run React.

Spend a few minutes clicking around the Components tab and exploring the different components. Click the inspector icon in the React Developer Tools, which appears in the upper left of the window and resembles the icon for the Chrome DevTools element inspector you saw earlier.

The React Developer Tools' element inspector works similarly to the Chrome DevTools' element inspector (and to the Firefox element inspector too, for that matter). The difference between these two tools is an essential one to understand, however. Whereas the browser's element inspector can be used to highlight and view the HTML and styles that are in the browser's DOM, the React element inspector allows you to highlight and view the React components that were rendered on the page. You can think of the Components tab as a higher-level view.

The React components you can inspect through the React Developer Tools eventually produce the DOM nodes (which represent HTML and styles) that you can browse using the browser's element inspector.

The Profiler gives you information about the performance of your React application. Profiling is disabled in the production version of React, so this tab won't do much when you view a public web page that uses React. We'll explore and use the Profiler and show how it can be used to debug and tune your React applications in Chapter 5.

Intro to Create React App

The most common way to get started with React is to use a node package called Create React App. Create React App is an officially supported tool that installs a toolchain for React development and configures a boilerplate React application that you can use as a starting point for your applications.

To install and run Create React App, you can use a command that comes as part of the npm package manager called npx. npx is a package runner. Earlier in this Introduction, you used the npm install command to install a node package. Once a package is installed, you can run it by using the npm start command. npx is similar to a combination of npm install and npm start. If the package is already installed globally on your computer when you issue a command to run it with npx, the already-installed package will be run. If it's not installed, running it with npx will cause it to be downloaded, temporarily installed locally, and run.

To create a new React app using Create React App, use the npx command, followed by create-react-app, followed by a name that you want to give your new React app. For example:

npx create-react-app my-new-app

Naming Your React App

The name you choose for your new app is up to you, as long as it conforms to the rules of Node.js package names. These rules are:

It must be less than 214 characters long.

The name can't start with a dot or underscore.

The name can't have uppercase letters.

It can't contain any characters that aren't allowed in URLs (such as ampersands and dollar signs) and that are “unsafe” in URLs (such as the percent symbol and spaces).

In addition to these rules, there are several common conventions for how Node.js packages, and therefore apps created using Create React App, are named:

Keep it simple and as short as possible.

Use only lowercase letters.

Use dashes in place of spaces.

Don't use the same name as a common Node.js package.

Making Your First React App

Follow these steps to use Create React App to make your first React app:

Make or open a new folder in Visual Studio Code.

Open the Terminal and make your new folder the working directory. You can do this by right-clicking the folder name and choosing

Open in Integrated Terminal

, or by opening the Terminal and using the Unix cd (for change directory) command to change the working directory to the one where you want to make the new app. Note that if you're using Windows, your integrated terminal may be the Windows Command Prompt, in which case the command to change the working directory is dir.

Use npx to run

create-react-app

and give your new application a name. For example:

npx create-react-app my-test-app

Press

Enter

to start the installation of

create-react-app

and the configuration of your new app. You'll see a series of messages and progress bars in the Terminal. You may also see some errors and warnings, but often these aren't anything to be concerned about.

When the installation and configuration of your new React app finishes, change to the directory containing your new app by typing

cd

followed by the name you gave to your app:

cd my-test-app

Start up your app by using the

npm start

command. Note: npm start is actually shorthand for

npm run start

. What you're doing when you run

npm start

is that you're causing a script called

start

to run its commands.

Wait and watch as your generated React app starts up and then opens in a browser to reveal the React logo and a message, as shown in

Figure I-16

.

FIGURE I-16: The default Create React App boilerplate

Open the Chrome DevTools window and use the Components pane that you installed with the React Developer Tools to inspect your React app. Notice that this sample app is much smaller and less complex than the one that makes up the

reactjs.org

website, which you inspected earlier in this Introduction.

Now that you've created a React app, you can try making some changes to it by following these steps:

Leave the integrated Terminal in Visual Studio Code open and open

src/App.js

, which is located inside your application's folder.

NOTE React applications are made up of a hierarchy of components, and this one is the top-level component, and the only one in a default application generated by Create React App.

Find the part of

App.js

that contains the code shown in

Listing 0-1

.

LISTING 0-1: The return statement in the default Create React App boilerplate

<div className="App">

<header className="App-header">

<img src={logo} className="App-logo" alt="logo"/>

<p>

Edit <code>src/App.js</code> and save to reload.

</p>

<a

className="App-link"

href="https://reactjs.org"

target="_blank"

rel="noopener noreferrer"

>

Learn React

</a>

</header>

</div>

NOTE The HTML-like syntax you see here is JSX, which is a special feature of React projects that we will cover in detail in Chapter 3.

Change the text between the

<p>

and

</p>

tags and then save

App.js

.

Switch back to your browser, and notice that the browser window has updated to reflect the change you made to

App.js

!

Congratulations, and Onward!

If you've made it this far, you're well on your way to learning React. You have your toolchain set up, you've learned the basics of using two in-browser testing tools (Chrome DevTools and React Developer Tools), you've installed Create React App, and you've used it to generate a boilerplate React application.

Feel free to play around with the tools and commands you learned in this Introduction, and to try making additional changes to the Create React App boilerplate code to see what happens.

When you're ready, move on to Chapter 1, where you'll get hands-on experience with building and modifying your first React components!

READER SUPPORT FOR THIS BOOK

You'll find hundreds of code listings in this book. I've designed these to be simple enough to be easily understandable, but practical enough to be helpful as you transition from learning React to practicing writing React code. To get the most out of this book, I recommend you try running and experimenting with each of the code listings.

To make running the examples easier, I've put them all online, including working examples where possible.

Companion Download Files

As you work through the examples in this book, you may choose either to type in all the code manually or to use the source code files that accompany the book. All the source code used in this book is available for download from http://www.wiley.com/go/reactjsfoundations.

Working examples of each code listing, supplemental information, and a link to the book's Github repository are available at https://www.reactjsfoundations.com.

If you prefer to download and run the example code on your own computer, you can clone the repository using Git and then follow the instructions in the README file to view working versions of every code listing.

If you don't have Git installed, you can go to https://www.reactjsfoundations.com in your browser and click the Download button to download all of the code to your computer.

In the event that a “but” may have made it into this book, or some unforeseen update to React has necessitated a change to any of the code in the book, you'll find corrections at https://www.reactjsfoundations.com as well.

How to Contact the Publisher

If you believe you've found a mistake in this book, please bring it to our attention. At John Wiley & Sons, we understand how important it is to provide our customers with accurate content, but even with our best efforts an error may occur.

In order to submit your possible errata, please email it to our Customer Service Team at [email protected] with the subject line “Possible Book Errata Submission.”