Learning React A Handson Guide To Building Web Applications Using React And Redux 2nd Edition Kirupa Chinnathambi download
Learning React A Handson Guide To Building Web Applications Using React And Redux 2nd Edition Kirupa Chinnathambi download
https://ebookbell.com/product/learning-react-a-handson-guide-to-
building-web-applications-using-react-and-redux-2nd-edition-
kirupa-chinnathambi-10441946
https://ebookbell.com/product/learning-react-a-handson-guide-to-
building-maintainable-highperforming-web-application-user-interfaces-
using-the-react-javascript-library-1st-edition-chinnathambi-7228934
Of Course Its A Big Deal A Story About Learning To React Calmly And
Appropriately Bryan Smith
https://ebookbell.com/product/of-course-its-a-big-deal-a-story-about-
learning-to-react-calmly-and-appropriately-bryan-smith-48666184
https://ebookbell.com/product/reach-every-athlete-a-guide-to-coaching-
players-with-hidden-disabilities-and-conditions-christopher-
stanley-48756406
https://ebookbell.com/product/reach-the-highest-standard-in-
professional-learning-learning-communities-1st-edition-shirley-m-hord-
patricia-a-roy-51282632
Learning React Modern Patterns For Developing React Apps 2nd Edition
Alex Banks
https://ebookbell.com/product/learning-react-modern-patterns-for-
developing-react-apps-2nd-edition-alex-banks-23007782
https://ebookbell.com/product/learning-react-native-building-native-
mobile-apps-with-javascript-bonnie-eisenman-42303170
https://ebookbell.com/product/learning-react-native-building-native-
mobile-apps-with-javascript-1-early-release-bonnie-eisenman-5207528
Learning React Functional Web Development With React And Redux Early
Release Raw Unedited 1st Edition Alex Banks
https://ebookbell.com/product/learning-react-functional-web-
development-with-react-and-redux-early-release-raw-unedited-1st-
edition-alex-banks-5771042
Learning React Native Building Native Mobile Apps With Javascript 2nd
Edition Bonnie Eisenman
https://ebookbell.com/product/learning-react-native-building-native-
mobile-apps-with-javascript-2nd-edition-bonnie-eisenman-7013730
Learning React
Second Edition
The Pearson Addison-Wesley
Learning Series
Each title comes with sample code for the application or applications built
in the text. This code is fully annotated and can be reused in your own
projects with no strings attached. Many chapters end with a series of
exercises to encourage you to reexamine what you have just learned, and
to tweak or adjust the code as a way of learning.
Titles in this series take a simple approach: they get you going right away
and leave you with the ability to walk off and build your own application
and apply the language or technology to whatever you are working on.
Kirupa Chinnathambi
Learning React, Second Edition Editor
Copyright © 2018 by Pearson Education, Inc. Mark Taber
All rights reserved. No part of this book shall be reproduced, stored in a retrieval system, Managing Editor
or transmitted by any means, electronic, mechanical, photocopying, recording, or otherwise, Sandra Schroeder
without written permission from the publisher. No patent liability is assumed with respect Project Editor
to the use of the information contained herein. Although every precaution has been taken Mandie Frank
in the preparation of this book, the publisher and author assume no responsibility for
errors or omissions. Nor is any liability assumed for damages resulting from the use of Copy Editor
the information contained herein. Krista Hansing
Indexer
ISBN-13: 978-0-13-484355-1
Erika Millen
ISBN-10: 0-13-484355-X
Proofreader
Library of Congress Control Number: 2017957370 Jeanine Furino
1 18 Technical Editor
Trevor McCauley
Trademarks
All terms mentioned in this book that are known to be trademarks or service marks have Editorial Assistant
been appropriately capitalized. Pearson cannot attest to the accuracy of this information. Vanessa Evans
Use of a term in this book should not be regarded as affecting the validity of any trademark Designer
or service mark. Chuti Prasertsith
Warning and Disclaimer Compositor
Every effort has been made to make this book as complete and as accurate as possible, codemantra
but no warranty or fitness is implied. The information provided is on an “as is” basis. The
author and the publisher shall have neither liability nor responsibility to any person or entity
with respect to any loss or damages arising from the information contained in this book.
Special Sales
For information about buying this title in bulk quantities, or for special sales opportunities
(which may include electronic versions; custom cover designs; and content particular to
your business, training goals, marketing focus, or branding interests), please contact our
corporate sales department at [email protected] or (800) 382-3419.
For government sales inquiries, please contact [email protected].
For questions about sales outside the U.S., please contact [email protected].
Accessing the Free Web Edition
Your purchase of this book in any format includes access to the corresponding
Web Edition, which provides several special online-only features:
■ The complete text of the book
■ Updates and corrections as they become available
The Web Edition can be viewed on all types of computers and mobile devices with
any modern web browser that supports HTML5.
To get access to the Learning React Web Edition, all you need to do is register
this book:
1. Go to www.informit.com/register.
5. The Web Edition will appear under the Digital Purchases tab on your
Account page. Click the Launch link to access the product.
❖
To my dad!
3 Components in React 23
4 Styling in React 37
6 Transferring Properties 65
7 Meet JSX…Again! 79
Index 267
Table of Contents
1 Introducing React 1
Old-School Multipage Design 2
New-School Single-Page Apps 3
Meet React 6
Automatic UI State Management 7
Lightning-Fast DOM Manipulation 7
APIs to Create Truly Composable UIs 8
Visuals Defined Entirely in JavaScript 10
Just the V in an MVC Architecture 12
Conclusion 12
3 Components in React 23
Quick Review of Functions 24
Changing How We Deal with UI 26
Meet the React Component 28
Creating a Hello, World! Component 29
Specifying Properties 32
First Part: Updating the Component Definition 33
Second Part: Modifying the Component Call 33
Dealing with Children 34
Conclusion 35
4 Styling in React 37
Displaying Some Vowels 37
Styling React Content Using CSS 40
Understand the Generated HTML 40
Just Style It Already! 41
Contents ix
6 Transferring Properties 65
Problem Overview 65
Detailed Look at the Problem 69
Meet the Spread Operator 74
A Better Way to Transfer Properties 75
Conclusion 77
7 Meet JSX…Again! 79
What Happens with JSX? 79
JSX Quirks to Remember 81
Evaluating Expressions 81
Returning Multiple Elements 82
You Can’t Specify CSS Inline 83
Comments 84
Capitalization, HTML Elements, and Components 85
Your JSX Can Be Anywhere 86
Conclusion 86
x Contents
Index 267
About the Author
Kirupa Chinnathambi has spent most of his life trying to teach others to love web
development as much as he does.
In 1999, before blogging was even a word, he started posting tutorials on kirupa.com. In the
years since then, he has written hundreds of articles, penned a few books (none as good as
this one, of course!), and recorded a bunch of videos you can find on YouTube. When he isn’t
writing or talking about web development, he spends his waking hours helping make the web
more awesome as a Program Manager at Microsoft. In his nonwaking hours, he is probably
sleeping—or writing about himself in the third person.
Acknowledgments
First, none of this would be possible without the support and encouragement of my awesome
wife, Meena. If she hadn’t put her goals on hold to allow me to spend six months designing,
writing, and rewriting everything you see here, writing this book would have been a distant
dream.
Next, I’d like to thank my parents for always encouraging me to aimlessly wander and enjoy
free time doing what I like—such as teaching complete strangers via the Internet in the late
1990s how to do cool things with programming. I wouldn’t be half the rugged indoorsman/
scholar/warrior I am today without them both .
On the publishing side, writing the words you see here is the easy part. Getting the book into
your hands is an amazingly complex process. The more I learn about all the moving pieces
involved, the more impressed I am with all the individuals who work tirelessly behind the
scenes to keep this amazing machinery running. To everyone at Pearson who made this
possible, thank you! There are a few people I’d like to explicitly call out, though. First, I’d like
to thank Mark Taber for continuing to give me opportunities to work together, Chris Zahn
for patiently addressing my numerous questions and concerns, Krista Hansing for turning my
version of English into something humanly understandable, and Loretta Yates for helping
make the connections a long time ago that made all of this happen. The technical content of
this book has been reviewed in great detail by my long-time friends and online collaborators
Kyle Murray (a.k.a. Krilnon) and Trevor McCauley (a.k.a. senocular). I can’t thank them
enough for their thorough (and, frequently, humorous!) feedback.
1
Introducing React
Ignoring for a moment that web apps today both look and feel nicer than they did back in the
day, something even more fundamental has changed. The way we architect and build web apps
is very different now. To highlight this, let’s take a look at the app in Figure 1.1.
This app is a simple catalog browser for something. As with any app of this sort, you have your
usual set of pages revolving around a home page, a search results page, a details page, and so
on. In the following sections, let’s look at the two approaches we have for building this app.
Yes, in some mysterious fashion, this leads to us getting an overview of React as well.
Onward!
2 Chapter 1 Introducing React
For almost every action that changes what the browser displays, the web app navigates you to
a whole different page. This is a big deal, beyond just the less-than-stellar user experience users
will see as pages get torn down and redrawn. This has a big impact on how you maintain your
app state. Except for storing user data via cookies and some server-side mechanism, you simply
don’t need to care. Life is good.
Figure 1.3 The individual page model is a bit dated, like this steam engine.
Instead, modern apps tend to adhere to what is known as a single-page app (SPA) model. This
model gives you a world in which you never navigate to different pages or ever even reload a
page. In this world, the different views of your app are loaded and unloaded into the same page
itself.
As users interact with our app, we replace the contents of the dotted red region with the data
and HTML that matches what the user is trying to do. The end result is a much more fluid
experience. You can even use a lot of visual techniques to have your new content transition
nicely, just like you might see in cool apps on your mobile device or desktop. This sort of stuff
is simply not possible when navigating to different pages.
All of this might sound a bit crazy if you’ve never heard of single-page apps, but there’s a very
good chance you’ve run into some of them in the wild. If you’ve ever used popular web apps
like Gmail, Facebook, Instagram, or Twitter, you’ve used a single-page app. In all those apps,
the content gets dynamically displayed without requiring you to refresh or navigate to a
different page.
Now, I’m making these single-page apps seem really complicated. That’s not entirely the case.
Thanks to a lot of great improvements in both JavaScript and a variety of third-party frame-
works and libraries, building single-page apps has never been easier. That doesn’t mean there’s
no room for improvement, though.
New-School Single-Page Apps 5
When building single-page apps, you’ll encounter three major issues at some point:
1. In a single-page application, you’ll spend the bulk of your time keeping your data in
sync with your UI. For example, if a user loads new content, do you explicitly clear out
the search field? Do you keep the active tab on a navigation element still visible? Which
elements do you keep on the page, and which do you destroy?
These are all problems that are unique to single-page apps. When navigating between
pages in the old model, we assumed everything in our UI would be destroyed and just
built back up again. This was never a problem.
2. Manipulating the DOM is really, really slow. Manually querying elements, adding
children (see Figure 1.5), removing subtrees, and performing other DOM operations is
one of the slowest things you can do in your browser. Unfortunately, in a single-page
app, you’ll be doing a lot of this. Manipulating the DOM is the primary way you are able
to react to user actions and display new content.
To make things worse, depending on the framework you’re using, the way your templates
look and interact with data can vary wildly. For example, this is what defining and using a
template in Mustache looks like:
var view = {
title: "Joe",
calc: function() {
return 2 + 4;
}
};
Sometimes your templates look like clean HTML that you can proudly show off in front of
the class. Other times, your templates might be unintelligible, with a boatload of custom
tags designed to help map your HTML elements to some data.
Despite these shortcomings, single-page apps aren’t going anywhere. They are a part of the
present and will fully form the future of how web apps are built. That doesn’t mean you have
to tolerate these shortcomings, of course. Read on.
Meet React
Facebook (and Instagram) decided that enough is enough. Given their huge experience with
single-page apps, they released a library called React to not only address these shortcomings,
but also change how we think about building single-page apps.
In the following sections, we look at the big things React brings to the table.
Meet React 7
Figure 1.6 The final or end state of your UI is what matters in React.
React takes care of everything else. It figures out what needs to happen to ensure that your UI
is represented properly so that all that state-management stuff is no longer your concern.
Figure 1.7 Imagine an in-memory virtual DOM that sort of looks like this.
Manipulating this virtual DOM is extremely fast, and React takes care of updating the real DOM
when the time is right. It does so by comparing the changes between your virtual DOM and the
real DOM, figuring out which changes actually matter, and making the fewest number of DOM
changes needed to keep everything up-to-date in a process called reconciliation.
Figure 1.8 An example of how the visuals of your app can be broken into smaller pieces.
As with everything else in programming, it’s a good idea to make things modular, compact, and
self-contained. React extends that well-worn idea to how we think about user interfaces. Many
of React’s core APIs revolve around making it easier to create smaller visual components that
can later be composed with other visual components to make larger and more complex visual
components—kind of like the Russian matryoshka dolls in Figure 1.9. (see Figure 1.8):
10 Chapter 1 Introducing React
This is one of the major ways React simplifies (and changes) how we think about building the
visuals for our web apps.
For example, here’s what a conditional statement inside an EmberJS template looks like:
{{#if person}}
Welcome back, {{person.firstName}} {{person.lastName}}!
{{else}}
Please log in.
{{/if}}
Meet React 11
React does something pretty neat. By having your UI defined entirely in JavaScript, you get
to use all the rich functionality JavaScript provides for doing all sorts of things inside your
templates. You are limited only by what JavaScript supports, not limitations imposed by
your templating framework.
Now, when you think of visuals defined entirely in JavaScript, you’re probably thinking
something horrible that involves quotation marks, escape characters, and a whole lot of
createElement calls. Don’t worry. React allows you to (optionally) specify your visuals
using an HTML-like syntax known as JSX that lives fully alongside your JavaScript. Instead
of writing code to define your UI, you are basically specifying markup:
ReactDOM.render(
<div>
<h1>Batman</h1>
<h1>Iron Man</h1>
<h1>Nicolas Cage</h1>
<h1>Mega Man</h1>
</div>,
destination
);
Yikes! Using JSX, you are able to easily define your visuals using a very familiar syntax, while
still getting all the power and flexibility that JavaScript provides.
Best of all, in React, your visuals and JavaScript often live in the same location. You no longer
have to jump among multiple files to define the look and behavior of one visual component.
This is templating done right.
Conclusion
As new web frameworks and libraries go, React is a runaway success. It not only deals with the
most common problems developers face when building single-page apps, but it also throws in a
few additional tricks that make building the visuals for your single-page apps much easier. Since
it came out in 2013, React has also steadily found its way into popular web sites and apps that
you probably use. Besides Facebook and Instagram, some notable ones include the BBC, Khan
Academy, PayPal, Reddit, The New York Times, and Yahoo!, among many others.
This article was an introduction to what React does and why it does it. In subsequent chapters,
we’ll dive deeper into everything you’ve seen here and cover the technical details that will help
you successfully use React in your own projects. Stick around.
2
Building Your
First React App
Thanks to the previous chapter, you probably now know all about the backstory of React and how
it helps even your most complex user interfaces sing. For all the awesomeness that React brings to
the table, getting started with it (kind of like this sentence) is not the most straightforward. It has
a steep learning curve filled with many small and big hurdles, as in Figure 2.1.
Figure 2.1 Hurdles come in a variety of sizes. Some are big. Some are small.
In this chapter, we start at the very beginning and get our hands dirty by building a simple
React app. You’ll encounter some of these hurdles head-on, and some of these hurdles you’ll
skip over—for now. By the end of this chapter, not only will you have built something you can
proudly show off to your friends and family, but you’ll have set yourself up nicely for diving
deeper into all that React offers in future chapters.
14 Chapter 2 Building Your First React App
As you know, your web apps (and everything else your browser displays) are made up of HTML,
CSS, and JavaScript (see Figure 2.2).
Figure 2.2 Web apps are built in HTML, CSS, and JavaScript.
It doesn’t matter whether your web app was written using React or some other library, such as
Angular, Knockout, or jQuery. The end result has to be some combination of HTML, CSS, and
JavaScript; otherwise, your browser really won’t know what to do.
Now, here’s where the special nature of React comes in. Besides normal HTML, CSS, and
JavaScript, the bulk of your React code will be written in JSX. As I mentioned in Chapter 1,
“Introducing React,” JSX is a language that allows you to easily mix JavaScript and HTML-like
tags to define user interface (UI) elements and their functionality. That sounds cool and all
(and you’ll see JSX in action in just a few moments), but there’s a slight problem. Your browser
has no idea what to do with JSX.
To build a web app using React, we need a way to convert our JSX into plain old JavaScript that
your browser can understand (see Figure 2.3).
Dealing with JSX 15
Figure 2.3 JSX needs to turn into something our browser understands.
If we don’t do this, our React app simply won’t work. That’s not cool. Fortunately, we have two
solutions to this:
2. Let your browser automatically convert JSX to JavaScript at runtime. You specify
your JSX directly, just as you would any old piece of JavaScript, and your browser takes
care of the rest.
Both of these solutions have a place in our world, but let’s talk about the impact of each.
The first solution, while a bit complicated and time-consuming at first, is the way modern
web development is done these days. Besides compiling (transpiling, to be more accurate) your
JSX to JS, this approach enables you to take advantage of modules, better build tools, and a
bunch of other features that make building complex web apps somewhat manageable.
The second solution provides a quick and direct path in which you initially spend more time
writing code and less time fiddling with your development environment. To use this solution,
all you do is reference a script file. This script file takes care of turning the JSX into JS on page
load, and your React app comes to life without you having to do anything special to your
development environment.
For our introductory look at React, we are going to use the second solution. You might be wondering
why we don’t always use the second solution. The reason is that your browser takes a perfor-
mance hit each time it translates JSX into JS. That is totally acceptable when learning how to
use React, but it is totally not acceptable when deploying your app for real-life use. Because of
that lack of acceptability, we will revisit all of this later, to look at the first solution and how to
set up your development environment after you’ve gotten your feet comfortably wet in React.
16 Chapter 2 Building Your First React App
<head>
<meta charset="utf-8">
<title>React! React! React!</title>
</head>
<body>
<script>
</script>
</body>
</html>
This page has nothing interesting or exciting going for it, but let’s fix that by adding a
reference to the React library. Just below the title, add these two lines:
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
These two lines bring in both the core React library and the various things React needs to work
with the DOM. Without them, you aren’t building a React app at all.
Now, you aren’t done yet. You need to reference one more library. Just below these two script
tags, add the following line:
<script src="https://unpkg.com/[email protected]/babel.min.js"></script>
Here you’re adding a reference to the Babel JavaScript compiler (http://babeljs.io/). Babel does
many cool things, but the one we care about is its capability to turn JSX into JavaScript.
Displaying Your Name 17
<head>
<meta charset="utf-8">
<title>React! React! React!</title>
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/[email protected]/babel.min.js"></script>
</head>
<body>
<script>
</script>
</body>
</html>
If you preview your page right now, you’ll notice that this page is still blank, with nothing
visible going on. That’s okay. We’re going to fix that next.
Don’t worry if none of this makes sense at this point. Our goal is to get something to display
onscreen first, and we’ll make sense of what we did afterward. Now, before previewing this in
the page to see what happens, you need to designate this script block as something that Babel
can work its magic on. You do that is by setting the type attribute on the script tag to a value
of text/babel:
<script type="text/babel">
ReactDOM.render(
<h1>Sherlock Holmes</h1>,
document.body
);
</script>
18 Chapter 2 Building Your First React App
After you’ve made that change, preview what you have in your browser. You’ll see the words
Sherlock Holmes printed in giant letters, as in Figure 2.4.
As apps go, this isn’t all that exciting. Chances are, your name isn’t even Sherlock Holmes. This
app doesn’t have much going for it, but it does introduce you to one of the most frequently
used methods you’ll use in the React universe: the ReactDOM.render method.
2. The location in the DOM where React will render the JSX into
Our first argument is the text Sherlock Holmes wrapped inside some h1 tags. This HTML-like
syntax inside your JavaScript is what JSX is all about. We’ll spend a lot more time drilling into
JSX a bit later, but I should mention this up front: It is every bit as crazy as it looks. Whenever
I see brackets and slashes in JavaScript, a part of me dies on the inside because of all the string
It’s All Still Familiar 19
escaping and quotation mark gibberish I will need to do. With JSX, you do none of that. You
just place your HTML-like content as is, just like you’ve done here. Magically (like the super-
awesome kind involving dragons and laser beams), it all works.
The second argument is document.body. There’s nothing crazy or bizarre about this argument.
It simply specifies where the converted markup from the JSX will end up living in our DOM. In
our example, when the render method runs, the h1 tag (and everything inside it) is placed in
our document’s body element.
Now, the goal of this exercise wasn’t to display a name on the screen. It was to display your
name. Go ahead and modify your code to do that. In my case, the render method will look as
follows:
ReactDOM.render(
<h1>Batman</h1>,
document.body
);
Well, it would look like that if my name were Batman! Anyway, if you preview your page now,
you’ll see your name displayed instead of Sherlock Holmes.
With the container div element safely defined, let’s modify the render method to use it
instead of document.body. Here’s one way of doing this:
ReactDOM.render(
<h1>Batman</h1>,
document.querySelector("#container")
);
ReactDOM.render(
<h1>Batman</h1>,
destination
);
Notice that the destination variable stores the reference to your container DOM element.
Inside the render method, you simply reference the same destination variable instead of
writing the full element-finding syntax as part of the argument itself. The reason for this is
simple: I want to show you that you’re still writing JavaScript and that render is just another
boring old method that happens to take two arguments.
Styling It Up!
Time for the last change before we call it a day. Right now, our names show up in whatever
default h1 styling the browser provides. That’s just terrible, so let’s fix that by adding some CSS.
Inside your head tag, let’s add a style block with the following CSS:
<style>
#container {
padding: 50px;
background-color: #EEE;
}
#container h1 {
font-size: 144px;
font-family: sans-serif;
color: #0080A8;
}
</style>
After you’ve added everything, preview your page. Notice that the text appears to have a
little more purpose than it did earlier, when it relied entirely on the browser’s default styling
(see Figure 2.5).
It’s All Still Familiar 21
This works because, after running all the React code, the DOM’s body contains our container
element with an h1 tag inside it. It doesn’t matter that the h1 tag was defined entirely inside
JavaScript in this JSX syntax or that your CSS was defined well outside the render method. The
end result of your React app is still going to be made up of some 100% organic (and cage-free!)
HTML, CSS, and JavaScript. If we had to see what this transpiled JavaScript looks like, it would
look a bit like the following:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>React! React! React!</title>
<script src="https://unpkg.com/react@16/umd/react.development.js">
</script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js">
</script>
<script src="https://unpkg.com/[email protected]/babel.min.js"></script>
<style>
#container {
padding: 50px;
background-color: #EEE;
}
#container h1 {
font-size: 144px;
font-family: sans-serif;
color: #0080A8;
}
22 Chapter 2 Building Your First React App
</style>
</head>
<body>
<div id="container"></div>
<script type="text/babel">
var destination = document.querySelector("#container");
ReactDOM.render(React.createElement(
"h1",
null,
"Batman"
), destination);
</script>
</body>
</html>
Notice that there’s nary a trace of React-like code in sight. (Also, we should use the word nary
more often in everyday conversation!)
Conclusion
If this is your first time building a React app, we covered a lot of ground here. One of the
biggest takeaways is that React is different than other libraries because it uses a whole new
language called JSX to define what the visuals will look like. You got a very small glimpse of
that here when we defined the h1 tag inside the render method.
JSX’s impact goes beyond how you define your UI elements. It also alters how you build
your app as a whole. Because your browser can’t understand JSX in its native representation,
you need to use an intermediate step to convert that JSX into JavaScript. One approach is to
build your app to generate the transpiled JavaScript output to correspond to the JSX source.
Another approach (the one we used here) is to use the Babel library to translate the JSX into
JavaScript on the browser itself. While the performance hit of doing this is not recommended
for live/production apps, when you’re familiarizing yourself with React, you can’t beat the
convenience.
In future chapters, we spend some time diving deeper into JSX and going beyond the render
method as we look at all the important things that make React tick.
Components are one of the pieces that make React, well, React! They’re one of the primary
ways you have for defining the visuals and interactions that make up what people see when
they use your app. Let’s say Figure 3.1 shows what your finished app looks like.
This is the finished sausage. During development, viewed through the lens of a React project,
things might look a little less appealing. Almost every part of this app’s visuals would be
wrapped inside a self-contained module known as a component. To highlight what “almost
every” means here, take a look at the diagram in Figure 3.2.
24 Chapter 3 Components in React
Each dotted line represents an individual component that is responsible for both what you see
and any interactions that it is responsible for. Don’t let this scare you. While this looks really
complicated, you will soon see that it will start to make a whole lot of sense once you’ve had
a chance to play with components and some of the awesome things they do—or, at least, try
really hard to do.
In a terrible world where functions don’t exist, you might have some code that looks as follows:
var speed = 10;
var time = 5;
alert(speed * time);
Quick Review of Functions 25
In a really chill world that involves functions, you can condense all that duplicated text into
something simple, like the following:
function getDistance(speed, time) {
var result = speed * time;
alert(result);
}
Our getDistance function removes all the duplicated code you saw earlier, and it takes speed
and time as arguments to allow you to customize the calculation that gets returned.
Doesn’t this look nicer? Functions provide another great value, too. Your functions (such as
the alert inside getDistance) can call other functions as part of their running. Take a look
at using a formatDistance function to change what getDistance returns:
function formatDistance(distance) {
return distance + " km";
}
This capability to have functions call other functions enables us to cleanly separate what
functions do. You don’t need to have one monolithic function that does everything under
the sun; you can distribute functionality across many functions that are specialized for
a particular type of task.
Best of all, after you make changes to how your functions work, you don’t have to do anything
extra to see the results of those changes. If the function signature didn’t change, any existing
calls to that function will just magically work and automatically pick up any new changes you
made to the function itself.
26 Chapter 3 Components in React
In a nutshell, functions are awesome. I know that. You know that. That’s why all of the code
we write has them all over the place.
That’s a pretty controversial statement, so let me highlight what I mean by looking at some
examples. Let’s go back and look at the render method we used in the previous chapter:
var destination = document.querySelector("#container");
ReactDOM.render(
<h1>Batman</h1>,
destination
);
Onscreen, you see the word Batman printed in giant letters, thanks to the h1 element. Let’s
change things up a bit. Say that we want to print the names of several other superheroes. To do
this, we modify our render method to look as follows:
var destination = document.querySelector("#container");
ReactDOM.render(
<div>
<h1>Batman</h1>
<h1>Iron Man</h1>
<h1>Nicolas Cage</h1>
<h1>Mega Man</h1>
</div>,
destination
);
Notice what you see here. We emit a div that contains the four h1 elements with our superhero
names.
Okay, so now we have four h1 elements that each contains the name of a superhero. What if
we want to change our h1 element to something like an h3 instead? We can manually update
all of these elements as follows:
var destination = document.querySelector("#container");
ReactDOM.render(
<div>
<h3>Batman</h3>
<h3>Iron Man</h3>
Changing How We Deal with UI 27
<h3>Nicolas Cage</h3>
<h3>Mega Man</h3>
</div>,
destination
);
If you preview what we have, you’ll see something that looks a bit unstyled and plain
(see Figure 3.3).
We don’t want to go crazy with the styling here. All we want to do is italicize all these names
by using the i tag, so let’s manually update what we render by making this change:
var destination = document.querySelector("#container");
ReactDOM.render(
<div>
<h3><i>Batman</i></h3>
<h3><i>Iron Man</i></h3>
<h3><i>Nicolas Cage</i></h3>
<h3><i>Mega Man</i></h3>
</div>,
destination
);
28 Chapter 3 Components in React
We went through each h3 element and wrapped the content inside some i tags. Can you start
to see the problem here? What we are doing with our UI is no different than having code
that looks as follows:
var speed = 10;
var time = 5;
alert(speed * time);
Every change we want to make to our h1 or h3 elements needs to be duplicated for every
instance of them. What if we want to do something even more complex than just modifying
the appearance of our elements? What if we want to represent something more complex than
the simple examples we’re using so far? What we’re doing right now won’t scale; manually
updating every copy of what we want to modify is time-consuming. It is also boring.
Now, here’s a crazy thought: What if everything awesome that we looked at about functions could
somehow be applied to how we define our app’s visuals? Wouldn’t that solve all the inefficiencies
we’ve highlighted in this section? As it turns out, the answer to that “what if” forms the core of
what React is all about. It’s time for you to say hello to the component.
Let’s start by building a couple of components together. To follow along, start with a blank
React document:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>React Components</title>
Meet the React Component 29
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/[email protected]/babel.min.js"></script>
</head>
<body>
<div id="container"></div>
<script type="text/babel">
</script>
</body>
</html>
Nothing exciting is going on in this page. As in the last chapter, this page is pretty barebones,
with just a reference to the React and Babel libraries and a div element that proudly sports
an id value of container.
Let’s re-create all of this by using a component. React gives us several ways of creating
components, but we are going to create them by using the class syntax. Go ahead and add
the following highlighted code just above the existing render method:
class HelloWorld extends React.Component {
ReactDOM.render(
<div>
<p>Hello, world!</p>
</div>,
document.querySelector("#container")
);
If the class syntax is foreign to you, first check out my online tutorial Using Classes in
JavaScript (https://www.kirupa.com/javascript/classy_way_to_create_objects.htm).
30 Chapter 3 Components in React
Getting back to our code, we have created a new component called HelloWorld. This is a
component because it extends React.Component. If it didn’t do that, it would just be an empty
class that doesn’t do much. Inside our class, you can put all sorts of methods to further define
what HelloWorld does. Some methods that you define are special, and React uses them to help
your components work their magic. One such mandatory property is render.
Go ahead and modify our HelloWorld component by adding the render method, as shown:
class HelloWorld extends React.Component {
render() {
}
}
Just like the render method you saw a few moments earlier as part of ReactDOM.render, the
render function inside a component is also responsible for dealing with JSX. Let’s modify our
render function to return Hello, componentized world!. Add the following highlighted line:
class HelloWorld extends React.Component {
render() {
return <p>Hello, componentized world!</p>
}
}
You’ve told the render function to return the JSX that represents the Hello, componentized
world! text. All that remains is to actually use this component. You use a component after
you’ve defined it by calling it. Here we call it from our old friend, the ReactDOM.render
method.
The way you call a component from it is a bit unique. Go ahead and replace the first argument
to ReactDOM.render with the following:
ReactDOM.render(
<HelloWorld/>,
document.querySelector("#container")
);
That isn’t a typo! The JSX we use for calling our HelloWorld component is the very HTML-like
<HelloWorld/>. If you preview your page in your browser, you’ll see the text Hello, compo-
nentized world! showing up on your screen. If you were holding your breath in suspense, you
can relax.
If you have difficulty relaxing after seeing the syntax we used for calling HelloWorld, stare at
the circle in Figure 3.4 a few moments.
Meet the React Component 31
Okay, back to reality. What we’ve done so far might seem crazy, but simply think of your
<HelloWorld/> component as a cool and new HTML tag whose functionality you fully have
control over. This means you can do all sorts of HTML-y things to it.
For example, go ahead and modify our ReactDOM.render method to look as follows:
ReactDOM.render(
<div>
<HelloWorld/>
</div>,
document.querySelector("#container")
);
We wrapped our call to the HelloWorld component inside a div element, and if you preview
this in your browser, everything still works. Let’s go one step further! Instead of having just
32 Chapter 3 Components in React
a single call to HelloWorld, let’s make a bunch of calls. Modify our ReactDOM.render method
to now look as follows:
ReactDOM.render(
<div>
<HelloWorld/>
<HelloWorld/>
<HelloWorld/>
<HelloWorld/>
<HelloWorld/>
<HelloWorld/>
</div>,
document.querySelector("#container")
);
Now you’ll see is a bunch of Hello, componentized world! text instances appear. Let’s do one
more thing before we move on to something shinier. Go back to our HelloWorld component
declaration and change the text you return to the more traditional Hello, world! value:
class HelloWorld extends React.Component {
render() {
return <p>Hello, world!</p>
}
}
Make this one change and then preview your example. This time around, all the various
HelloWorld calls we specified earlier return Hello, world! to the screen. No need to manually
modify every HelloWorld call—that’s a good thing!
Specifying Properties
Right now, our component does just one thing. It prints Hello, world! to the screen—and only
that! That’s the equivalent of having a JavaScript function that looks like this:
function getDistance() {
alert("42km");
}
Except for one very specific case, that JavaScript function doesn’t seem very useful, does it? To
increase the usefulness of this function, we need to modify it to take arguments:
function getDistance(speed, time) {
var result = speed * time;
alert(result);
}
Now this function can be used more generally for a variety of situations, not just one whose
output will be 42km.
Something similar applies to your components as well. Just as with functions, you can pass in
arguments that alter what your component does. There’s a slight terminology update you need
Meet the React Component 33
to be on top of. What we call arguments in the function world are known as properties in the
component world. Let’s see these properties in action!
You’re now going to modify the HelloWorld component to allow you to specify who or what
you greet besides the generic World. For example, imagine being able to specify Bono as part of
the HelloWorld call and seeing Hello, Bono! appear onscreen.
To specify the value of greetTarget as part of our component, we need to make this
modification:
class HelloWorld extends React.Component {
render() {
return <p>Hello, {this.props.greetTarget}!</p>
}
}
You access a property by referencing it via the this.props property that every component has
access to. Notice how you specify this property: You place it inside curly brackets, { and }. In JSX,
if you want something to get evaluated as an expression, you need to wrap that something inside curly
brackets. If you don’t do that, you’ll see the raw text this.props.greetTarget printed out.
Each HelloWorld call now has the greetTarget attribute, along with the name of a super-
hero (or equivalent mythical being) that we want to greet. If you preview this example in the
browser, you’ll see the greetings happily printed out onscreen.
One last point is important to call out before we move on. You are not limited to having just a
single property on a component. You can have as many properties as you want, and your props
property will easily accommodate any property requests you have without making any fuss.
Here you have a component very cleverly called CleverComponent, and it has a p element as
a child. From within CleverComponent, you have the capability to access the p child element
(and any children it has) via the children property accessed by this.props.children.
To make sense of all this, let’s look at another really simple example. This time around, we have
a component called Buttonify that wraps its children inside a button. The component looks
like this:
class Buttonify extends React.Component {
render() {
return(
<div>
<button type={this.props.behavior}>{this.props.children}</button>
</div>
);
}
}
You can use this component by calling it via the ReactDOM.render method, as shown here:
ReactDOM.render(
<div>
<Buttonify behavior="submit">SEND DATA</Buttonify>
</div>,
document.querySelector("#container")
);
When this code runs, given what the JSX in the Buttonify component’s render method
looked like, you see the words SEND DATA wrapped inside a button element. With the
appropriate styling, the result could look comically large, as in Figure 3.5.
Conclusion 35
Getting back to the JSX, notice that we specify a custom property called behavior. This property
allows us to specify the button element’s type attribute, and you can see us accessing it via
this.props.behavior in the component definition’s render method.
There’s more to accessing a component’s children than what you’ve seen here. For example,
if your child element is just some text, the this.props.children property returns a string.
If your child element is just a single element (as in our example), the this.props.children
property returns a single component that is not wrapped inside an array. We still need to call
out a few more things, but instead of enumerating all the cases and boring you, we’ll bring up
those points later as we look at more elaborate examples.
Conclusion
If you want to build an app using React, you can’t wander too far without having to use a
component. Trying to build a React app without using a component is kind of like building a
JavaScript-based app without using functions. I’m not saying that it can’t be done; it’s just one
of those things you don’t do—kind of like the Bad Idea part of the popular Animaniacs Good
Idea/Bad Idea sketches (https://www.youtube.com/watch?v=2dJOIf4mdus).
If this witty video doesn’t convince you that you should learn to embrace components, I don’t
know what will—except for maybe a future chapter on creating complex components!
»M. Dumas étoit avec nous. Nous fûmes le prendre chez lui.
L'Assemblée, également sur la présentation des comités, lui avoit
confié le commandement général de toutes les forces que nous
jugerions utile et nécessaire de requérir. Cette nomination n'est pas
indifférente. M. Dumas étoit la créature des Lameth.
»Nous voilà donc partis par un très-bon temps. Les postillons, qui
savoient l'objet de notre voyage, nous conduisoient avec la plus
grande rapidité. Dans les villages, dans les bourgs, dans les villes,
partout sur notre passage on nous donnoit des témoignages de joie,
d'amitié et de respect.
»M. Dumas n'étoit pas dans la même voiture que nous. Sortant de
Dormans, M. Dumas examinoit tous les endroits comme un général
d'armée. «Si M. de Bouillé arrive, disoit-il, il ne peut prendre que par
là; on peut l'arrêter à cette hauteur et ce défilé; sa cavalerie ne peut
plus manœuvrer.» Il fit même une disposition militaire. Il donna
ordre à la garde nationale d'un bourg de prendre tel et tel poste.
»Nous dîmes au Roi qu'il étoit dans les convenances que nous
prissions place dans sa voiture. Barnave et moi nous y entrâmes. À
peine y eurent-nous mis le premier pied que nous dîmes au Roi:
«Mais, Sire, nous allons vous gêner, vous incommoder; il est
impossible que nous trouvions place ici.» Le Roi répondit: «Je désire
qu'aucune des personnes qui m'ont accompagné ne sorte. Je vous
prie de vous asseoir, nous allons nous presser, vous trouverez
place.»
»Nous n'avions pas fait dix pas qu'on nous renouvelle les
protestations que le Roi ne vouloit pas sortir du royaume, et qu'on
nous témoigne les plus vives inquiétudes sur le sort des trois gardes
du corps qui étoient sur le siége de la voiture. Les paroles se
pressoient, se croisoient; chacun disoit la même chose; il sembloit
que c'étoit le mot du gué; mais il n'y avoit aucune mesure, aucune
dignité dans cette conversation, et je n'aperçus surtout sur aucune
des figures cette grandeur souvent très-imprimante que donne le
malheur à des âmes élevées.
»Le Roi parla d'un accident qui venoit d'arriver à un seigneur qui
venoit d'être égorgé, et il en paroissoit très-affecté. La Reine répétoit
que c'étoit abominable, qu'il faisoit beaucoup de bien dans sa
paroisse, et que c'étoient ses propres habitants qui l'avoient
assassiné.
»Madame Élisabeth me fixoit avec des yeux attendris, avec cet air
de langueur que le malheur donne et qui inspire un assez vif
intérêt.....
»Le Roi étoit seul dans une chambre où il y avoit un mauvais lit
d'auberge. Il passa la nuit dans un fauteuil.
»La Reine causa aussi avec moi d'une manière unie et familière;
elle me parla aussi de l'éducation de ses enfants. Elle en parla en
mère de famille et en femme assez instruite. Elle exposa des
principes très-justes en éducation. Elle dit qu'il falloit éloigner de
l'oreille des princes toute flatterie, qu'il ne falloit jamais leur dire que
la vérité. Mais j'ai su depuis que c'étoit le jargon de mode dans
toutes les cours de l'Europe. Une femme très-éclairée me rapportoit
qu'elle avoit vu et assez familièrement cinq ou six princesses qui
toutes lui avoient tenu le même langage, sans pour cela s'occuper
une minute de l'éducation de leurs enfants.
»Je vis bien cependant qu'elle désiroit qu'on lui crût du caractère;
elle répétoit assez souvent qu'il falloit en avoir, et il se présenta une
circonstance où elle me fit voir qu'elle le faisoit consister en si peu
de chose que je demeurai convaincu qu'elle n'en avoit pas.
»Le Roi vint lui-même sur la terrasse nous engager à dîner avec
lui. Nous conférâmes, MM. Maubourg, Barnave et moi, pour savoir si
nous accepterions. «Cette familiarité, dit l'un, pourroit paroître
suspecte.—Comme ce n'est pas l'étiquette, dit l'autre, on pourroit
croire que c'est à l'occasion de la situation malheureuse qu'il nous a
invités.» Nous convînmes de refuser, et nous fûmes lui dire que nous
avions besoin de nous retirer pour notre correspondance, ce qui
nous empêchoit de répondre à l'honneur qu'il nous faisoit.
»On servit le Roi ainsi que sa famille dans une salle séparée; on
nous servit dans une autre. Les repas furent splendides. Nous nous
mîmes à cinq heures en marche. En sortant de la Ferté, il y eut du
mouvement et du bruit autour de la voiture. Les citoyens forçoient la
garde nationale, la garde nationale vouloit empêcher d'approcher. Je
vis un de nos députés, Kervelegan, qui perçoit la foule, qui
s'échauffoit avec les gardes nationaux qui cherchoient à l'écarter, et
qui approcha de la portière en jurant, en disant: «Pour une brute
comme celle-là, voilà bien du train.» J'avançai ma tête hors de la
portière pour lui parler; il étoit très-échauffé, il me dit: «Sont-ils tous
là? prenez garde, car on parle encore de les enlever; vous êtes là
environnés de gens bien insolents!» Il se retira, et la Reine me dit
d'un air très-piqué et un peu effrayé: «Voilà un homme bien
malhonnête!» Je lui répondis qu'il se fâchoit contre la garde qui avoit
agi brusquement à son égard. Elle me parut craindre, et le jeune
prince jeta deux ou trois cris de frayeur.
«Eh bien, lui dis-je, madame, je vais vous parler avec toute
franchise, et je pense que je ne vous serai pas suspect. Je suis un de
ceux que l'on désigne sous le titre de républicains, et, si vous le
voulez, un des chefs de ce parti. Par principe, par sentiment, je
préfère le gouvernement républicain à tout autre. Il seroit trop long
de développer ici mon idée, car il est telle et telle république que
j'aimerois moins que le despotisme d'un seul. Mais il n'est que trop
vrai, je ne demande pas que vous en conveniez, mais il n'est que
trop vrai que presque partout les rois ont fait le malheur des
hommes; qu'ils ont regardé leurs semblables comme leur propriété;
qu'entourés de courtisans, de flatteurs, ils échappent rarement aux
vices de leur éducation première. Mais, madame, est-il exact de dire
qu'il existe maintenant un parti républicain qui veuille renverser la
constitution actuelle pour en élever une autre sur ses ruines? On se
plaît à le répandre pour avoir le prétexte de former également un
autre parti hors la constitution, un parti royaliste non constitutionnel,
pour exciter des troubles intérieurs. Le piége est trop grossier. On ne
peut pas, de bonne foi, se persuader que le parti appelé républicain
soit redoutable; il est composé d'hommes sages, d'hommes à
principes d'honneur qui savent calculer et qui ne hasarderoient pas
un bouleversement général qui pourroit conduire plus facilement au
despotisme qu'à la liberté.
»Ah! madame, que le Roi eût été bien conduit s'il eût favorisé
sincèrement la révolution! Les troubles qui nous agitent
n'existeroient pas, et déjà la constitution marcheroit, les ennemis du
dehors nous respecteroient; le peuple n'est que trop porté à chérir
et idolâtrer ses rois.»
»Je ne puis dire avec quelle énergie, avec quelle abondance d'âme
je lui parlai; j'étois animé par les circonstances et surtout par l'idée
que les germes de vérité que je jetois pourroient fructifier; que la
Reine se souviendroit de ce moment d'entretien.»
»Lorsque ces postes furent une fois remplis par les grenadiers, il
n'y eut plus de dispute; nous marchions sans obstacles, à la vérité
très-lentement. Au lieu d'entrer dans Paris par la porte Saint-Denis,
nous fîmes le tour des murs et nous passâmes par la porte de la
Conférence.
»Nous dîmes au Roi qu'il étoit nécessaire qu'il nous donnât les
noms des trois gardes du corps, ce qu'il fit.
ebookbell.com