1. React in Action 1st Edition Mark Tielens Thomas
install download
https://ebookmeta.com/product/react-in-action-1st-edition-mark-
tielens-thomas/
Download more ebook from https://ebookmeta.com
2. We believe these products will be a great fit for you. Click
the link to download now, or visit ebookmeta.com
to discover even more!
Cloud Native Spring in Action 1st Edition Thomas Vitale
https://ebookmeta.com/product/cloud-native-spring-in-action-1st-
edition-thomas-vitale/
Administrative Law in Action : Immigration
Administration 1st Edition Robert Thomas
https://ebookmeta.com/product/administrative-law-in-action-
immigration-administration-1st-edition-robert-thomas/
DuckDB in Action MEAP V03 Mark Needham Michael Hunger
Michael Simons
https://ebookmeta.com/product/duckdb-in-action-meap-v03-mark-
needham-michael-hunger-michael-simons/
Australian Practical Accounting Guide Stephen J.
Marsden
https://ebookmeta.com/product/australian-practical-accounting-
guide-stephen-j-marsden/
3. Leveled Text Dependent Question Stems Social Studies
1st Edition Niomi Henry
https://ebookmeta.com/product/leveled-text-dependent-question-
stems-social-studies-1st-edition-niomi-henry/
Fourier Series Fourier Transform and Their Applications
to Mathematical Physics Instructor Solution Manual
Solutions 1st Edition Valery Serov
https://ebookmeta.com/product/fourier-series-fourier-transform-
and-their-applications-to-mathematical-physics-instructor-
solution-manual-solutions-1st-edition-valery-serov/
Spanish Verb Tenses Dorothy Richmond
https://ebookmeta.com/product/spanish-verb-tenses-dorothy-
richmond/
Games and Education Designs in and for Learning 1st
Edition Hans Christian Arnseth
https://ebookmeta.com/product/games-and-education-designs-in-and-
for-learning-1st-edition-hans-christian-arnseth/
Her Dragon Mate Awaken the Dragon Book 4 1st Edition
Milly Taiden Ava Hunter
https://ebookmeta.com/product/her-dragon-mate-awaken-the-dragon-
book-4-1st-edition-milly-taiden-ava-hunter/
4. How to Diagnose and Fix Everything Electronic Second
Edition Michael Jay Geier
https://ebookmeta.com/product/how-to-diagnose-and-fix-everything-
electronic-second-edition-michael-jay-geier/
12. vii
brief contents
PART 1 MEET REACT.................................................................1
1 ■ Meet React 3
2 ■ <Hello World />: our first component 22
PART 2 COMPONENTS AND DATA IN REACT ..............................57
3 ■ Data and data flow in React 59
4 ■ Rendering and lifecycle methods in React 77
5 ■ Working with forms in React 111
6 ■ Integrating third-party libraries with React 129
7 ■ Routing in React 151
8 ■ More routing and integrating Firebase 170
9 ■ Testing React components 192
PART 3 REACT APPLICATION ARCHITECTURE..........................219
10 ■ Redux application architecture 221
11 ■ More Redux and integrating Redux with React 251
12 ■ React on the server and integrating React Router 277
13 ■ An introduction to React Native 313
Licensed to Samir Mashlum <smashlum@gmail.com>
14. ix
contents
preface xv
acknowledgments xvii
about this book xix
about the author xxii
about the cover illustration xxiii
PART 1 MEET REACT.......................................................1
1 Meet React 3
1.1 Meet React 4
Who this book is for 6 ■
A note on tooling 7
Who uses React? 7
1.2 What does React not do? 9
Tradeoffs of React 10
1.3 The virtual DOM 12
The DOM 13 ■
The virtual DOM 15 ■
Updates and
diffing 16 ■
Virtual DOM: Need for speed? 17
1.4 Components: The fundamental unit of React 17
Components in general 17 ■
Components in React: Encapsulated
and reusable 18
1.5 React for teams 19
Licensed to Samir Mashlum <smashlum@gmail.com>
15. CONTENTS
x
2 <Hello World />: our first component 22
2.1 Introducing React components 24
Understanding the application data 26 ■ Multiple components:
Composition and parent-child relationships 28 ■ Establishing
component relationships 28
2.2 Creating components in React 31
Creating React elements 31 ■ Rendering your first component 34
Creating React components 36 ■ Creating React classes 37
The render method 37 ■ Property validation via PropTypes 38
2.3 The life and times of a component 42
A React state of mind 43 ■ Setting initial state 44
2.4 Meet JSX 52
Creating components using JSX 53 ■ Benefits of JSX and
differences from HTML 55
PART 2 COMPONENTS AND DATA IN REACT ....................57
3 Data and data flow in React 59
3.1 Introducing state 60
What is state? 60 ■
Mutable and immutable state 63
3.2 State in React 65
Mutable state in React: Component state 65 ■
Immutable state in
React: Props 69 ■
Working with props: PropTypes and default
props 70 ■
Stateless functional components 71
3.3 Component communication 73
3.4 One-way data flow 74
4 Rendering and lifecycle methods in React 77
4.1 Getting set up with the Letters Social repo 78
Getting the source code 80 ■
Which version of node should
I use? 80 ■
Note on tooling and CSS 81 ■
Deploying 81
The API server and database 81 ■
Running the app 82
4.2 The render process and lifecycle methods 82
Introducing lifecycle methods 82 ■
Types of lifecycle methods 84
Initial and “will” methods 88 ■
Mounting components 89
Updating methods 93 ■
Unmounting methods 96
Catching errors 98
4.3 Starting to create Letters Social 102
Licensed to Samir Mashlum <smashlum@gmail.com>
16. CONTENTS xi
5 Working with forms in React 111
5.1 Creating posts in Letters Social 112
Data requirements 112 ■ Component overview and
hierarchy 113
5.2 Forms in React 115
Getting started with forms 115 ■ Form elements and events 116
Updating state in forms 120 ■ Controlled and uncontrolled
components 121 ■ Form validation and sanitization 123
5.3 Creating new posts 126
6 Integrating third-party libraries with React 129
6.1 Sending posts to the Letters Social API 130
6.2 Enhancing your component with maps 132
Creating the DisplayMap component using refs 133
Creating the LocationTypeAhead component 139
Updating CreatePost and adding maps to posts 145
7 Routing in React 151
7.1 What is routing? 152
Routing in modern front-end web applications 153
7.2 Creating a router 154
Component routing 155 ■
Creating the <Route />
component 156 ■
Starting to build the <Router/>
component 157 ■
Matching URL paths and parameterized
routing 160 ■
Adding routes to the Router component 162
8 More routing and integrating Firebase 170
8.1 Using the router 171
Creating a page for a post 177 ■
Creating a <Link/>
component 178 ■
Creating a <NotFound/> component 182
8.2 Integrating Firebase 183
Ensuring a user is logged in 187
9 Testing React components 192
9.1 Types of testing 194
Why test? 195
9.2 Testing React components with Jest, Enzyme, and React-
test-renderer 197
Licensed to Samir Mashlum <smashlum@gmail.com>
17. CONTENTS
xii
9.3 Writing your first tests 199
Getting started with Jest 199 ■ Testing a stateless functional
component 201 ■ Testing the CreatePost component without
Enzyme 205 ■ Test coverage 213
PART 3 REACT APPLICATION ARCHITECTURE................219
10 Redux application architecture 221
10.1 The Flux application architecture 223
Meet Redux: A variation on Flux 226 ■
Getting set up for
Redux 227
10.2 Creating actions in Redux 229
Defining action types 230 ■
Creating actions in Redux 232
Creating the Redux store and dispatching actions 232
Asynchronous actions and middleware 235 ■
To Redux or
not to Redux? 242 ■
Testing actions 245 ■
Creating custom
Redux middleware for crash reporting 247
11 More Redux and integrating Redux with React 251
11.1 Reducers determine how state should change 252
State shape and initial state 253 ■
Setting up reducers to respond
to incoming action 254 ■
Combining reducers together in our
store 261 ■
Testing reducers 262
11.2 Bringing React and Redux together 264
Containers vs. presentational components 264 ■
Using
<Provider /> to connect components to the Redux store 267
Binding actions to component event handlers 272 ■
Updating
your tests 274
12 React on the server and integrating React Router 277
12.1 What is server-side rendering? 278
Digging into server-side rendering 280
12.2 Why render on the server? 282
12.3 You might not need SSR 285
12.4 Rendering components on the server 286
12.5 Switching to React Router 292
Setting up React router 293
12.6 Handling authenticated routes with React router 297
12.7 Server rendering with data-fetching 301
Licensed to Samir Mashlum <smashlum@gmail.com>
18. CONTENTS xiii
13 An introduction to React Native 313
13.1 Introducing React Native 314
13.2 React and React Native 317
13.3 When to use React Native 319
13.4 The simplest “Hello World” 321
13.5 Where to go next 324
index 327
Licensed to Samir Mashlum <smashlum@gmail.com>
20. xv
preface
When I first started learning about and using React, the JavaScript community was just
beginning to settle down from a period of rapid innovation and disruption (read: tur-
bulence). React was gaining in popularity, but the JavaScript community still seemed
like the Wild West in many ways. I was excited about React as a technology because it
showed real promise. The mental model seemed solid, components made building
UIs easier, the API was flexible and expressive, and the whole project seemed like it
was “just right.” Postulations about its API surface, usability, and theoretical underpin-
nings aside, there was also the fact that it seemed really cool to me and I enjoyed work-
ing with it.
Since then, quite a bit has changed—and at the same time not much has changed at
all. React has remained largely the same in terms of its fundamental concepts and API,
although a body of knowledge and best practices have emerged and evolved, and more
people use it. An open source ecosystem of libraries and related technologies has flour-
ished. There are conferences, meetups, and communities that involve React to one
degree or another. In version 16, the React core team rewrote the internal architecture
of React in a way that both maintained backward compatibility and paved the way for a
slew of future innovations. All these “changes without too much change” point to what I
believe is one of React’s greatest strengths: a maintained tension between stability and
innovation that drives adoption without leaving people in the dust.
For all these reasons and more, React has continued to take hold as a technology
and has only become more popular. It’s in use in one way or another at many large
companies, at countless startups, and at every sort of company in between. And many
Licensed to Samir Mashlum <smashlum@gmail.com>
21. PREFACE
xvi
companies that don’t currently use React are trying to switch over to it to modernize
their frontend applications.
React hasn’t only grown in popularity with respect to the web—it’s also made
inroads into other platforms. React Native, the port of React to mobile platforms, has
also been a major innovation. It demonstrates React’s “learn once, write anywhere”
approach. This idea of React as a platform means you’re not limited to using it for
browser-based applications.
Let’s forget the hype around React and focus on what this book should do for you.
My primary hopes for React in Action are that it equips you to understand and work
with React effectively and, even more, that it makes you better at building user inter-
faces overall, even if in a small way. My aim is not to engage in buzzword-driven devel-
opment or push you toward “magical” technologies. Rather, my wager is that a robust
mental model and deep understanding coupled with practical examples will put you
in a place to do incredible things with React, whether on your own or with others.
Licensed to Samir Mashlum <smashlum@gmail.com>
22. xvii
acknowledgments
Don’t wait for things to be perfect before you share them with others.
Show early and show often. It’ll be pretty when we get there, but it won’t
be pretty along the way.
—Ed Catmull, Creativity, Inc.: Overcoming the Unseen Forces That Stand
in the Way of True Inspiration
Few worthwhile endeavors are undertaken alone. In many cases, a single person or
handful of people is entirely credited with success, but this singular attribution belies
the larger network of contributors who work toward an end. Those who would claim
to have “done it alone” often fail to realize the ways in which others have helped them,
whether by example or by instruction. What’s more, failure to realize the strength of
working in a community pushes success and excellence even further out of reach.
Working alone means being limited to what you, and only you, can do. Collaboration
provides a path to excellence by opening us to humility, new ideas, different perspec-
tives, and invaluable feedback.
I won’t be so foolish as to think, even for a second, that I’ve written this book by
myself. My fingers pushed keys, and my name will be on the cover, but that doesn’t
mean this was a one-person show. No, this book—like all the things in my life that I’m
grateful for—is the result of a rich community of smart, humble, loving people willing
to be patient, kind, and sometimes firm with me.
First, I would like to thank my wife, Haley. She’s my joy, my best friend, my creative
partner. She’s put up with this book for a long time. Late nights, more late nights, and
endless talking about the book. She—the brilliant and better writer—helped me when
Licensed to Samir Mashlum <smashlum@gmail.com>
23. ACKNOWLEDGMENTS
xviii
I had writer’s block. She encouraged me when I felt as if finishing the book was impos-
sible. She’s always constant in love and in prayer. She’s always comforted me in low
times, challenged me when I doubted myself, and celebrated with me in times of joy.
She’s been incredible through the entire process and I can’t wait to return the favor
and help her with the many books she’ll write in the future. I’m always and immeasur-
ably grateful for her.
I would also like to thank the other people in my life who have supported me in
this process. I’m humbled and thankful to have an incredible family. My mom and
dad, Annmarie and Mitchell, have been encouraging throughout the writing of this
book (and my whole life). They’ve also promised to read it in its entirety, though I
won’t hold them to that. My brothers, David and Peter, have also been supportive and
encouraging. They haven’t promised to read the book, though, so I’ll be reading it
aloud to them for the next year (or however long it takes). My friends from church,
childhood, and work have also been incredibly helpful. They did me the great service
of always asking, “Is it done yet?” to spur me on, and they put up with my explanations
of React. I would also like to thank my professors, especially Dr. Diana Pavlac Glyer, for
teaching me to think and to write.
The folks at Manning have been very helpful in this process. I want to extend a spe-
cial thank you to Marina Michaels (development editor), Nickie Bruckner (technical
development editor), and German Frigerio (technical proofer). They spent countless
hours reading and helping with my writing. This book wouldn’t exist without them. I
would also like to thank Brian Sawyer for reaching out to me about writing the book
and Marjan Bace for giving me the opportunity to write the book in the first place.
Everyone at Manning is committed to helping people everywhere learn important,
impactful skills and concepts in effective ways. I firmly believe in and am excited to
help further Manning’s educational mission.
Licensed to Samir Mashlum <smashlum@gmail.com>
24. xix
about this book
React in Action is about React, the library for building user interfaces on the web. It
covers the core concepts and APIs involved in building React applications. You’ll build
a sample social networking application with React over the course of the book. This
app will cover a variety of topics, ranging from adding dynamic data to rendering on
the server.
Audience
This book is written for people who want to learn React. It doesn’t matter if you’re a
software engineer, a VP of engineering, a CTO, a designer, an engineering manager,
a university or coding boot camp student, or someone who’s just curious about React.
Depending on what your needs are, you can focus on different parts of the book, too.
I cover React from a high level during the first part of the book and get more specific
and advanced as we go.
You’ll have a better experience reading the book if you have some basic familiarity
with JavaScript. This book uses a lot of JavaScript, but it isn’t about JavaScript. I don’t
cover fundamental concepts in JavaScript, although I do lightly touch on them if
they’re relevant to a discussion about React. You should be able to work through the
examples if you have a basic proficiency with JavaScript and understand how asyn-
chronous programming in JavaScript works.
React in Action also assumes that you know some of the basics of building a front-
end web application from a technology perspective—knowing about the basic browser
APIs will be helpful. You’ll work with things like the Fetch API to make network
Licensed to Samir Mashlum <smashlum@gmail.com>
25. ABOUT THIS BOOK
xx
requests, set and get cookies, and work with user events (typing, clicks, and so on).
You’ll also interact heavily with libraries (although not too many!). Familiarity with
the basics of a modern frontend application will help you get the most out of this
book.
Fortunately, I’ve abstracted away all the complexity around tooling and the build
process that’s also a requisite part of building modern web applications. The source
code for the project includes all the necessary dependencies and build tools, so you
don’t have to understand, for example, how Webpack and Babel work in order to
enjoy this book. All in all, you should have at least a basic proficiency with JavaScript
and some frontend web application concepts to fully enjoy React in Action.
Roadmap
React in Action’s 13 chapters are divided into 3 parts.
Part 1, “Meet React,” introduces you to React. Chapter 1 covers core ideas of React
at a high level. It talks about some of the key points of React, shows how it might fit
into your development process, and looks at what React does and doesn’t do. Chapter
2 is the “show me the code” chapter. You’ll dive into React’s APIs and build a simple
comment box with React components.
Part 2, “Components and data in React,” is where you’ll start to go deeper with
React. You’ll see how data flows in React in chapter 3 and look at the component life-
cycle API and start building the Letters Social sample project in chapter 4. This proj-
ect will take us through the remainder of the book. Chapter 4 goes over setting up the
project from the application source code and explains how to work with it for the rest
of the book.
Chapters 5 through 9 are an even deeper dive into React. Chapter 5 covers work-
ing with forms and gives you another opportunity to work with data and data flow in
React. Chapter 6 follows in the same vein and builds on the work done in chapter 5 to
create a more complex React component for displaying maps.
Chapters 7 and 8 tackle routing, a crucial part of almost any modern frontend
application. You’ll build a router from scratch and get your app set up to handle mul-
tiple pages. You’ll keep going with routing in chapter 8 and integrate the Firebase
platform so you can authenticate users. Chapter 9 closes out part 3 by introducing
testing React apps and components.
Part 3, “React application architecture,” covers more advanced topics in React and
focuses especially on transitioning your application to use Redux. Chapters 10 and 11
introduce Redux, a state-management solution. Once your app is transitioned to use
Redux, we’ll explore server-side rendering in chapter 12. This chapter also covers
switching out your custom-built router for React Router. Chapter 13 briefly discusses
React Native, another React project that allows you to write JavaScript React apps for
mobile devices (iOS and Android).
Licensed to Samir Mashlum <smashlum@gmail.com>
26. ABOUT THIS BOOK xxi
About the code
React in Action uses two main groups of source code. For the first two chapters, you’ll
work with code outside the project repository. You’ll be able to run these code samples
on Codesandbox.io, an online code playground. It takes care of bundling your code
and running it in real time, so you don’t have to worry about setting up a build process.
In chapter 4, you’ll get set up with the project source code. It’s available for down-
load at the book’s website, www.manning.com/books/react-in-action, and on GitHub
online at https:/
/github.com/react-in-action/letters-social, and the final result of the
project is live at https:/
/social.react.sh. Each chapter or range of chapters has its own
branch in Git, so you can easily switch into a later chapter or follow the progression of
the project throughout the book. The source code all lives on GitHub, so feel free to
ask questions on GitHub or on the book’s forum at https:/
/forums.manning.com/
forums/react-in-action.
The JavaScript for the app should all be formatted using Prettier (https:/
/
github.com/prettier/prettier), written using the most current ECMAScript specifica-
tion (which is ES2017 at time of writing). Prettier uses concepts, syntax, and methods
available in that specification. The project includes an ESLint configuration, but if
you prefer to modify it to suit your own needs, feel free.
Software and hardware requirements
React in Action doesn’t have any strict hardware requirements. You’re free to use any
type of computer (physical or a virtual provider like Cloud9 https:/
/c9.io), although I
won’t address inconsistencies caused by differences in development environments. If
these issues come up for individual packages, the repositories for those packages or
Stack Overflow (https:/
/stackoverflow.com) are the best place to seek help.
As for software, here are a few requirements and recommendations:
■ The build process for the sample project uses node.js (https:/
/nodejs.org), so
you’ll need to install the latest stable version. See chapter 4 for more on getting
set up with node.js.
■ You’ll also need a text editor and a web browser. I recommend something like
Visual Studio Code (https:/
/code.visualstudio.com), Atom (https:/
/atom.io), or
Sublime Text (www.sublimetext.com).
■ You’ll use Chrome as the main browser for the course of the book, especially its
developer tools. Download it at www.google.com/chrome.
Licensed to Samir Mashlum <smashlum@gmail.com>
27. xxii
about the author
Mark Tielens Thomas is a full-stack software engineer and
author. He and his wife live and work in southern California.
Mark enjoys tackling large-scale engineering problems and lead-
ing teams to deliver high-impact, high-value solutions. He loves
Jesus, good coffee, too many books, fast APIs, and beautiful sys-
tems. He writes for Manning and on his personal blog at https:/
/
ifelse.io.
Licensed to Samir Mashlum <smashlum@gmail.com>
28. xxiii
about the cover illustration
The caption for the illustration on the cover of React in Action is “The Capitan Pasha,
Derya Bey, admiral of the Turkish navy.” The capitan pasha was a high-admiral with
supreme command of the navy of the Ottoman Empire. The illustration is taken from
a collection of costumes of the Ottoman Empire published on January 1, 1802, by
William Miller of Old Bond Street, London. The title page is missing from the collec-
tion, and we have been unable to track it down to date. The book’s table of contents
identifies the figures in both English and French, and each illustration bears the
names of two artists who worked on it, both of whom would no doubt be surprised to
find their art gracing the front cover of a computer programming book ... two hun-
dred years later.
The collection was purchased by a Manning editor at an antiquarian flea market in
the “Garage” on West 26th Street in Manhattan. The seller was an American based in
Ankara, Turkey, and the transaction took place just as he was packing up his stand for
the day. The Manning editor didn’t have on his person the substantial amount of cash
that was required for the purchase, and a credit card and check were both politely
turned down. With the seller flying back to Ankara that evening, the situation was get-
ting hopeless. What was the solution? It turned out to be nothing more than an old-
fashioned verbal agreement sealed with a handshake. The seller simply proposed that
the money be transferred to him by wire, and the editor walked out with the bank
information on a piece of paper and the portfolio of images under his arm. Needless
to say, we transferred the funds the next day, and we remain grateful and impressed by
Licensed to Samir Mashlum <smashlum@gmail.com>
29. ABOUT THE COVER ILLUSTRATION
xxiv
this unknown person’s trust in one of us. It recalls something that might have hap-
pened a long time ago.
We at Manning celebrate the inventiveness, the initiative, and, yes, the fun of the
computer business with book covers based on the rich diversity of regional life of two
centuries ago, brought back to life by the pictures from this collection.
Licensed to Samir Mashlum <smashlum@gmail.com>
30. Part 1
Meet React
If you’ve worked on frontend JavaScript applications in the past two years,
you’ve probably heard of React. You might have heard of it even if you’re just start-
ing out building user interfaces. Even if you’re hearing about React for the first
time in this book, I’ve still got you covered: there are many hugely popular appli-
cations that use React. If you use Facebook, watch Netflix, or learn about com-
puter science through Khan Academy, you’ve used an application built with React.
React is a library for building user interfaces. It was created by engineers at
Facebook and since its release has made waves in the JavaScript communities. It’s
gained in popularity over the past few years and is the tool of choice for many
teams and engineers building dynamic user interfaces. In fact, the combination of
React’s API, mental model, and robust community have led to the development of
React for other platforms, including mobile and even virtual reality.
In this book, you’ll explore React and see why it’s been such a successful and
useful open source project. In part 1, you’ll start with the basics of React and learn
them from the ground up. Because the tooling involved in building robust JavaS-
cript UI applications can be incredibly complex, we’ll avoid getting bogged down
in tools and focus on learning the ins and outs of the React API. We’ll also avoid
“magic” and work toward a concrete understanding of React and how it works.
In chapter 1, you’ll learn about React at a high level. We’ll cover some
important ideas like components, the virtual DOM, and some of the tradeoffs of
React. In chapter 2, you’ll take a whirlwind tour through React’s APIs and build
a simple comment-box component to get your hands dirty with React.
Licensed to Samir Mashlum <smashlum@gmail.com>
32. 3
Meet React
If you work as a web engineer in the tech industry, chances are you’ve heard of
React. Maybe it was somewhere online like Twitter or Reddit. Maybe a friend or col-
league mentioned it to you or you heard a talk about it at a meetup. Wherever it
was, I bet that what you heard was probably either glowing or a bit skeptical. Most
people tend to have a strong opinion about technologies like React. Influential and
impactful technologies tend to generate that kind of response. For these technolo-
gies, often a smaller number of people initially “get it” before the technology
catches on and moves to a broader audience. React started this way, but now enjoys
immense popularity and use in the web engineering world. And it’s popular for
This chapter covers
Introducing React
Some of React’s high-level concepts and
paradigms
The virtual DOM
Components in React
React for teams
Tradeoffs of using React
Licensed to Samir Mashlum <smashlum@gmail.com>
33. 4 CHAPTER 1 Meet React
good reason: it has a lot to offer and can reinvigorate, renew, or even transform how
you think about and build user interfaces.
1.1 Meet React
React is a JavaScript library for building user interfaces across a variety of platforms.
React gives you a powerful mental model to work with and helps you build user inter-
faces in a declarative and component-driven way. We’ll unpack these ideas and much
more over the course of the book, but that’s what React is in the broadest, briefest sense.
Where does React fit into the broader world of web engineering? You’ll often hear
React talked about in the same space as projects like Vue, Preact, Angular, Ember, Web-
pack, Redux and other well-known JavaScript libraries and frameworks. React is often a
major part of front-end applications and shares similar features with the other libraries
and frameworks just mentioned. In fact, many popular front-end technologies are more
like React in subtle ways now than in the past. There was a time when React’s approach
was novel, but other technologies have since been influenced by React’s component-
driven, declarative approach. React continues to maintain a spirit of rethinking estab-
lished best practices, with the main goal being providing developers with an expressive
mental model and a performant technology to build UI applications.
What makes React’s mental model powerful? It draws on deep areas of computer
science and software engineering techniques. React’s mental model draws broadly on
functional and object-oriented programming concepts and focuses on components as
primary units for building with. In React applications, you create interfaces from com-
ponents. React’s rendering system manages these components and keeps the applica-
tion view in sync for you. Components often correspond to aspects of the user
interface, like datepickers, headers, navbars, and others, but they can also take
responsibility for things like client-side routing, data formatting, styling, and other
responsibilities of a client-side application.
Components in React should be easy to think about and integrate with other React
components; they follow a predictable lifecycle, can maintain their own internal state,
and work with “regular old JavaScript.” We’ll dive into these ideas over the course of
the rest of the book, but we can look at them at a high level right now. Figure 1.1 gives
you an overview of the major ingredients that go into a React application. Let’s look at
each part briefly:
Components—Encapsulated units of functionality that are the primary unit in
React. They utilize data (properties and state) to render your UI as output; we’ll
explore how React components work with data later in chapter 2 onward. Cer-
tain types of React components also provide a set of lifecycle methods that you
can hook into. The rendering process (outputting and updating a UI based on
your data) is predictable in React, and your components can hook into it using
React’s APIs.
React libraries—React uses a set of core libraries. The core React library works
with the react-dom and react-native libraries and is focused on component
Licensed to Samir Mashlum <smashlum@gmail.com>
34. 5
Meet React
specification and definition. It allows you to build a tree of components that a
renderer for the browser or another platform can use. react-dom is one such
renderer and is aimed at browser environments and server-side rendering. The
React Native libraries focus on native platforms and let you create React appli-
cations for iOS, Android, and other platforms.
Components
Other JavaScript
(other modules, custom methods)
<Component
display
userID={12}>
<OtherComponent/>
<Component>
{"user": {name: "Mark"}}
componentWillMount
componentDidMount
componentWillReceiveProps
shouldComponentUpdate
componentWillUpdate
componentDidUpdate
componentWillUnmount
Application
Application code (components, styles, utilities, business logic)
React
React DOM / React-
Native / React VR
Other libraries
Native devices
(iOS, Android)
VR Devices
(React VR)
Server
(node.js)
Desktop &
Mobile
Props
Internal component state Lifecycle methods
Target environments/platforms
Figure 1.1 React allows you to create user interfaces from components.
Components maintain their own state, are written in and work with “vanilla”
JavaScript, and inherit a number of helpful APIs from React. Most React apps
are written for browser-based environments, but can also be used in native
environments like iOS and Android. For more about React Native, see Nader
Dabit’s React Native in Action, also available from Manning.
Licensed to Samir Mashlum <smashlum@gmail.com>
35. 6 CHAPTER 1 Meet React
Third-party libraries—React doesn’t come with tools for data modeling, HTTP
calls, styling libraries, or other common aspects of a front-end application. This
leaves you free to use additional code, modules, or other tools you prefer in
your application. And even though these common technologies don’t come
bundled with React, the broader ecosystem around React is full of incredibly
useful libraries. In this book, we’ll use a few of these libraries and devote chap-
ters 10 and 11 to looking at Redux, a library for state management.
Running a React application—Your React application runs on the platform you’re
building for. This book focuses on the web platform and builds a browser and
server-based application, but other projects like React Native and React VR
open the possibility of your app running on other platforms.
We’ll spend lots of time exploring the ins and outs of React in this book, but you
may have a few questions before getting started. Is React something for you? Who
else is using React? What are some of the tradeoffs of using React or not? These are
important questions about a new technology that you’ll want answered before
adopting it.
1.1.1 Who this book is for
This book is for anyone who’s working on or interested in building user interfaces.
Really, it’s is for anyone who’s curious about React, even if you don’t work in UI engi-
neering. You’ll get the most out of this book if you have some experience with using
JavaScript to build front-end applications.
You can learn how to build applications with React as long as you know the basics
of JavaScript and have some experience building web applications. I don’t cover the
fundamentals of JavaScript in this book. Topics like prototypal inheritance, ES2015+
code, type coercion, syntax, keywords, asynchronous coding patterns like async/await,
and other fundamental topics are beyond the scope of this book. I do lightly cover
anything that’s especially pertinent to React but don’t dive deep into JavaScript as a
language.
This doesn’t mean you can’t learn React or won’t get anything from this book if
you don’t know JavaScript. But you’ll get much more if you take the time to learn
JavaScript first. Charging ahead without a working knowledge of JavaScript will make
things more difficult. You might run into situations where things might seem like
“magic” to you—things will work, but you won’t understand why. This usually hurts
rather than helps you as a developer, so ... last warning: get comfortable with the
basics of JavaScript before learning React. It’s a wonderfully expressive and flexible
language. You’ll love it!
You may already know JavaScript well and may have even dabbled in React before.
This wouldn’t be too surprising given how popular React has become. If this is you,
you’ll be able to gain a deeper understanding of some of the core concepts of React.
But I don’t cover highly specific topics you may be looking for if you’ve been working
Licensed to Samir Mashlum <smashlum@gmail.com>
36. 7
Meet React
with React for a while. For those, see other React-related Manning titles like React
Native in Action.
You may not fit into either group and may want a high-level overview of React. This
book is for you, too. You’ll learn the fundamental concepts of React and you’ll have
access to a sample application written in React—check out the running app at
https:/
/social.react.sh. You’ll be able to see the basics of building a React application
in practice and how it might be suited to your team or next project.
1.1.2 A note on tooling
If you’ve worked extensively on front-end applications in the past few years, you won’t
be surprised by the fact that the tooling around applications has become as much a
part of the development process as frameworks and libraries themselves. You’re likely
using something like Webpack, Babel, or other tools in your applications today. Where
do these and other tools fit into this book, and what you need to know?
You don’t need to be a master of Webpack, Babel, or other tools to enjoy and read
this book. The sample application I’ve created utilizes a handful of important tools,
and you can feel free to read through the configuration code for these in the sample
application, but I don’t cover these tools in depth in this book. Tooling changes
quickly, and more importantly, it would be well outside the scope of this book to cover
these topics in depth. I’ll be sure to note anywhere tooling is relevant to our discus-
sion, but besides that I’ll avoid covering it.
I also feel that tooling can be a distraction when learning a new technology like
React. You’re already trying to get your head around a new set of concepts and para-
digms—why clutter that with learning complex tooling too? That’s why chapter 2
focuses on learning "vanilla” React first before moving on to features like JSX and
JavaScript language features that require build tools. The one area of tooling that
you’ll need to be familiar with is npm. npm is the package management tool for Java-
Script, and you’ll use it to install dependencies for your project and run project com-
mands from the command line. It’s likely you’re already familiar with npm, but if not,
don’t let that dissuade you from reading the book. You only need the most basic termi-
nal and npm skills to go forward. You can learn about npm at https:/
/docs.npmjs
.com/getting-started/what-is-npm.
1.1.3 Who uses React?
When it comes to open source software, who is (and who isn’t) using it is more than just
a matter of popularity. It affects the experience you’ll have working with the technology
(including availability of support, documentation, and security fixes), the level of innova-
tion in the community, and the potential lifetime of a certain tool. It’s generally more
fun, easier, and overall a smoother experience to work with tools that have a vibrant com-
munity, a robust ecosystem, and a diversity of contributor experience and background.
React started as a small project but now has broad popularity and a vibrant com-
munity. No community is perfect, and React’s isn’t either, but as far as open source
Licensed to Samir Mashlum <smashlum@gmail.com>
37. 8 CHAPTER 1 Meet React
communities go, it has many important ingredients for success. What’s more, the
React community also includes smaller subsets of other open source communities.
This can be daunting because the ecosystem can seem vast, but it also makes the
community robust and diverse. Figure 1.2 shows a map of the React ecosystem. I
mention various libraries and projects throughout the course of the book, but if
you’re curious to learn more about the React ecosystem, I’ve put together a guide at
https:/
/ifelse.io/react-ecosystem. I’ll keep this updated over time and ensure it evolves
as the ecosystem does.
The primary way you might interact with React is probably in open source, but you
likely use apps built with it every day. Many companies use React in different and
exciting ways. Here are a few of the companies using React to power their products:
Portal to Preact Mirror World
JavaScript Ocean
Bay of Jest
The United State(s)
of Management
Fluxville
Reduxopolis
Mobxton
JavaScript
Fatigue Cove
Upper GraphQLton
Relay Town
Utilitopia
The Monadic
Kingdom of FP
Immutable City
Tutorialandia
React VR
WebAssembly
Future Reconciler Research
Uncharted territory
Tooling Town
Babel Transpilation
Institutes
The Great
Bundle Forges
CSS Plains
Styled Components
CSS Modules
Glamor(ous)
Aphrodite
Styletron
Radium forest
Downtown React
TC39 Embassy
Center for Twitter
Thought-leadership React High Council
Conference
Center
Reconciler
Research
Center
Large DOM
Reconciler
Central Github
Repository
Serverland
The Testing Narrows
Enzyme
Bend
Component
Canyon
React Native
Bridge
The React Ecosystem
Copyright Mark Thomas 2017
Figure 1.2 A map of the React ecosystem is diverse—even more so than I can represent here. If you’d like to
learn more, check out my guide at https:/
/ifelse.io/react-ecosystem, which will help you find your way in the
React ecosystem when starting out.
Licensed to Samir Mashlum <smashlum@gmail.com>
38. 9
What does React not do?
These companies aren’t blindly following the trends of the JavaScript community.
They have exceptional engineering demands that impact a huge number of users and
must deliver products on hard deadlines. Someone saying, “I heard React was good;
we should React-ify everything!” won’t fly with managers or other engineers. Compa-
nies and developers want good tools that help them think better and move quickly so
they can build high-impact, scalable, and reliable applications.
1.2 What does React not do?
So far, I’ve been talking about React at a high-level: who uses it, who this book is for,
and so on. My primary goals in writing this book are to teach you how to build applica-
tions with React and empower you as an engineer. React isn’t perfect, but it’s genu-
inely been a pleasure to work with, and I’ve seen teams do great things with it. I love
writing about it, building with it, hearing talks about it at conferences, and engaging
in the occasional spirited debate about this or that pattern.
But I would be doing you a disservice if I didn’t talk about some of the downsides
of React and describe what it doesn’t do. Understanding what something can’t do is as
important as understanding what it can do. Why? The best engineering decisions and
thinking usually happen in terms of tradeoffs instead of opinions or absolutes (“React
is fundamentally better than tool X because I like it more”). On the former point:
you’re probably not dealing with two totally different technologies (COBOL versus
JavaScript); hopefully you’re not even considering technologies that are fundamentally
unsuited to the task at hand. And to the latter point: building great projects and solv-
ing engineering challenges should never be about opinions. It’s not that people’s
opinions don’t matter—that’s certainly not true—it’s that opinions don’t make things
work well or at all.
■ Facebook ■ Asana
■ Netflix ■ ESPN
■ New Relic ■ Walmart
■ Uber ■ Venmo
■ Wealthfront ■ Codecademy
■ Heroku ■ Atlassian
■ PayPal ■ Asana
■ BBC ■ Airbnb
■ Microsoft ■ Khan Academy
■ NFL ■ FloQast
■ And more!
Licensed to Samir Mashlum <smashlum@gmail.com>
39. 10 CHAPTER 1 Meet React
1.2.1 Tradeoffs of React
If tradeoffs are the bread and butter of good software evaluation and discussion, what
tradeoffs are there with React? First, React is sometimes called just the view. This can be
misconstrued or misunderstood because it can lead you to think React is just a tem-
plating system like Handlebars or Pug (née Jade) or that it has to be part of an MVC
(model-view-controller) architecture. Neither is true. React can be both of those
things, but it can be much more. To make things easier, I’ll describe React more in
terms of what it is than what it’s not (“just the view,” for example). React is a declarative,
component-based library for building user interfaces that works on a variety of platforms:
web, native, mobile, server, desktop, and even on virtual reality platforms going for-
ward (React VR).
This leads to our first tradeoff: React is primarily concerned with the view aspects
of UI. This means it’s not built to do many of the jobs of a more comprehensive frame-
work or library. A quick comparison to something like Angular might help drive this
point home. In its most recent major release, Angular has much more in common
with React than it previously did in terms of concepts and design, but in other ways it
covers much more territory than React. Angular includes opinionated solutions for
the following:
HTTP calls
Form building and validation
Routing
String and number formatting
Internationalization
Dependency injection
Basic data modeling primitives
Custom testing framework (although this isn’t as important a distinction as the
other areas)
Service workers included by default (a worker-style approach to executing
JavaScript)
That’s a lot, and in my experience there are generally two ways people tend to react1
to all these features coming with a framework. Either it’s along the lines of “Wow, I
don’t have to deal with all those myself” or it’s “Wow, I don’t get to choose how I do
anything.” The upside of frameworks like Angular, Ember, and the like is that there’s
usually a well-defined way to do things. For example, routing in Angular is done with
the built-in Angular Router, HTTP tasks are all done with the built-in HTTP routines,
and so on.
There’s nothing fundamentally wrong with this approach. I’ve worked on teams
where we used technologies like this and I’ve worked on teams where we went the
1
Pun not intended but, hey, it’s a book about React, so there it is.
Licensed to Samir Mashlum <smashlum@gmail.com>
40. 11
What does React not do?
more flexible direction and chose technologies that “did one thing well.” We did great
work with both kinds of technologies, and they served their purposes well. My per-
sonal preference is toward the choose-your-own, does-one-thing-well approach, but
that’s really neither here nor there; it’s all about tradeoffs. React doesn’t come with
opinionated solutions for HTTP, routing, data modeling (although it certainly has
opinions about data flow in your views, which we’ll get to), or other things you might
see in something like Angular. If your team sees this as something you absolutely can’t
do without in a singular framework, React might not be your best choice. But in my
experience, most teams want the flexibility of React coupled with the mental model
and intuitive APIs that it brings.
One upside to the flexible approach of React is that you’re free to pick the best
tools for the job. Don’t like the way X HTTP library works? No problem—swap it out
for something else. Prefer to do forms in a different way? Implement it, no problem.
React provides you with a set of powerful primitives to work with. To be fair, other
frameworks like Angular will usually allow you to swap things out too, but the de
facto and community-backed way of doing things will usually be whatever is built-in
and included.
The obvious downside to having more freedom is that if you’re used to a more
comprehensive framework like Angular or Ember, you’ll need to either come up with
or find your own solution for different areas of your application. This can be a good
thing or a bad thing, depending on factors like developer experience on your team,
engineering management preferences, and other factors specific to your situation.
There are plenty of good arguments for the one-size-fits-all as well as the does-one-
thing-well approaches. I tend to be more convinced by the approach that lets you
adapt and make flexible, case-by-case decisions about tooling over time in a way that
entrusts engineering teams with the responsibility to determine or create the right
tools. There’s also the incredibly broader JavaScript ecosystem to consider—you’ll be
hard-pressed to find nothing aimed at a problem you’re solving. But at the end of the
day, the fact remains that excellent, high-impact teams use both sorts of approaches
(sometimes at the same time!) to build out their products.
I’d be remiss if I didn’t mention lock-in before moving on. It’s an unavoidable fact
that JavaScript frameworks are rarely truly interoperable; you can’t usually have an
app that’s part Angular, part Ember, part Backbone, and part React, at least not with-
out segmenting off each part or tightly controlling how they interact. It doesn’t usu-
ally make sense to put yourself in that sort of situation when you can avoid it. You
usually go with one and maybe temporarily, at most, two primary frameworks for a par-
ticular application.
But what happens when you need to change? If you use a tool with wide-ranging
responsibilities like Angular, migrating your app is likely going to be a complete
rewrite due to the deep idiomatic integration of your framework. You can rewrite
smaller parts of the application, but you can’t just swap out a few functions and expect
everything to work. This is an area where React can shine. It employs relatively few
Licensed to Samir Mashlum <smashlum@gmail.com>
41. 12 CHAPTER 1 Meet React
“magic” idioms. That doesn’t mean it makes migration painless, but it does help you
to potentially forgo incurring the cost of a tightly integrated framework like Angular if
you migrate to or from it.
Another tradeoff you make when choosing React is that it’s primarily developed
and built by Facebook and is meant to serve the UI needs of Facebook. You might
have a hard time working with React if your application is fundamentally different
than the UI needs of Facebook’s apps. Fortunately, most modern web apps are in
React’s technological wheelhouse, but there are certainly apps that aren’t. These
might also include apps that don’t work within the conventional UI paradigms of
modern web apps or apps that have very specific performance needs (such as a high-
speed stock ticker). Yet even these can often be addressed with React, though some sit-
uations require more-specific technologies.
One last tradeoff we should discuss is React’s implementation and design. Baked
into the core of React are systems that handle updating the UI for you when the data
in your components change. They execute changes that you can hook into using cer-
tain methods called lifecycle methods. I cover these extensively in later chapters. React’s
systems that handle updating your UI make it much easier to focus on building modu-
lar, robust components that your application can use. The way React abstracts away
most of the work of keeping a UI up-to-date with data is a big part of why developers
enjoy working with it so much and why it’s a powerful primitive in your hands. But it
shouldn’t be assumed that there are no downsides or tradeoffs made with respect to
the “engines” that power the technology.
React is an abstraction, so the costs of it being an abstraction still remain. You
don’t get as much visibility into the system you’re using because it’s built in a particu-
lar way and exposed through an API. This also means you’ll need to build your UI in
an idiomatically React way. Fortunately, React’s APIs provide “escape hatches” that let
you drop down into lower levels of abstraction. You can still use other tools like
jQuery, but you’ll need to use them in a React-compatible way. This again is a tradeoff:
a simpler mental model at the cost of not being able to do absolutely everything how
you’d like.
Not only do you lose some visibility to the underlying system, you also buy into
the way that React does things. This tends to impact a narrower slice of your applica-
tion stack (only views instead of data, special form-building systems, data modeling,
and so on), but it affects it nonetheless. My hope is that you’ll see that the benefits
of React far outweigh the cost of learning it and that the tradeoffs you make when
using it generally leave you in a much better place as a developer. But it would be
disingenuous for me to pretend that React will magically solve all your engineering
challenges.
1.3 The virtual DOM
We’ve talked a little bit about some of the high-level features of React. I’ve posited that
it can help you and your team become better at creating user interfaces and that part
Licensed to Samir Mashlum <smashlum@gmail.com>
42. 13
The virtual DOM
of this is due to the mental model and APIs that React provides. What’s behind all
that? A major theme in React is a drive to simplify otherwise complex tasks and
abstract unnecessary complexity away from the developer. React tries to do just
enough to be performant while freeing you up to think about other aspects of your
application. One of the main ways it does that is by encouraging you to be declarative
instead of imperative. You get to declare how your components should behave and look
under different states, and React’s internal machinery handles the complexity of man-
aging updates, updating the UI to reflect changes, and so on.
One of the major pieces of technology driving this is the virtual DOM. A virtual
DOM is a data structure or collection of data structures that mimics or mirrors the
Document Object Model that exists in browsers. I say a virtual DOM because other
frameworks such as Ember employ their own implementation of a similar technology.
In general, a virtual DOM will serve as an intermediate layer between the application
code and the browser DOM. The virtual DOM allows the complexity of change detec-
tion and management to be hidden from the developer and moved to a specialized
layer of abstraction. In the next sections, we’ll look from a high level at how this works
in React. Figure 1.3 shows a simplified overview of the DOM and virtual DOM rela-
tionship that we’ll explore shortly.
1.3.1 The DOM
The best way to ensure that we understand React’s virtual DOM is to start by checking
our understanding of the DOM. If you already feel you have a deep understanding of
JavaScript Interpreter
Browser
Browser “native” engine
Actual DOM
Virtual DOM
Synthetic
Event system
Optimized
updates
Input,
events,
status
Figure 1.3 The DOM and virtual DOM. React’s virtual DOM handles change detection in data as
well as translating browser events into events that React components can understand and react
to. React’s virtual DOM also aims to optimize changes made to the DOM for the sake of
performance.
Licensed to Samir Mashlum <smashlum@gmail.com>
43. 14 CHAPTER 1 Meet React
the DOM, feel free to move ahead. But if not, let’s start with an important question:
what is the DOM? The DOM, or Document Object Model, is a programming interface
that allows your JavaScript programs to interact with different types of documents
(HTML, XML, and SVG). There are standards-driven specifications for it, which
means that a public working group has created a standard set of features it should
have and ways it should behave. Although other implementations exist, the DOM is
mostly synonymous with web browsers like Chrome, Firefox, and Edge.
The DOM provides a structured way of accessing, storing, and manipulating differ-
ent parts of a document. At a high level, the DOM is a tree structure that reflects the
hierarchy of an XML document. This tree structure is comprised of sub-trees that are
in turn made of nodes. You’ll probably know these as the divs and other elements that
make up your web pages and applications.
You’ve probably used the DOM API before—but you may not have known you
were using it. Whenever you use a method in JavaScript that accesses, modifies, or
stores information related to something in an HTML document, you’re almost cer-
tainly using the DOM or its related APIs (see https:/
/developer.mozilla.org/en-
US/docs/Web/API for more on web APIs). This means that not all the methods
you’ve used in JavaScript are necessarily part of the JavaScript language itself (docu-
ment.findElemenyById, querySelectorAll, alert, and so on). They’re part of the
bigger collection of web APIs—the DOM and other APIs that go into a browser—that
allow you to interact with documents. Figure 1.4 shows a simplified version of the
DOM tree structure you’ve probably seen in your web pages.
Common methods or properties you may have used to update or query a web page
might include getElementById, parent.appendChild, querySelectorAll, innerHTML,
Element:
<title>
Element
<head>
innerText:
“React”
Document
Root element
<html>
Element:
<a>
innerText:
“React is cool”
Element:
<h1>
innerText:
“Welcome”
Element
<body>
Figure 1.4 Here’s a simple version of the DOM tree structure, using elements
you’re probably familiar with. The DOM API that’s exposed to JavaScript lets
you performs operations on these elements in the tree.
Licensed to Samir Mashlum <smashlum@gmail.com>
44. 15
The virtual DOM
and others. These are all provided by the host environment (in this case, the browser)
and allow JavaScript to interact with the DOM. Without this ability, we’d have far less
interesting web apps to use and perhaps no books about React to write!
Interacting with the DOM is usually straightforward but can get complicated in the
context of a large web application. Fortunately, we don’t often need to directly inter-
act with the DOM when building applications with React—we mostly leave that to
React. There are cases when we want to reach out past the virtual DOM and interact
with the DOM directly, and we’ll cover those in future chapters.
1.3.2 The virtual DOM
The web APIs in browsers let us interact with web documents with JavaScript via the
DOM. But if we can already do this, why do we need something else in between? I
want to first state that React’s implementation of a virtual DOM doesn’t mean that the
regular web APIs are bad or inferior to React. Without them, React can’t work. There
are, however, certain pain points of working directly with the DOM in larger web
applications. Generally, these pain points arise in the area of change detection. When
data changes, we want to update the UI to reflect that. Doing that in a way that’s effi-
cient and easy to think about can be difficult, so React aims to solve that problem.
Part of the reason for that problem is the way browsers handle interactions with
the DOM. When a DOM element is accessed, modified, or created, the browser is
often performing a query across a structured tree to find a given element. That’s just
to access an element, which is usually only the first part of an update. More often than
not, it may have to reperform layout, sizing, and other actions as part of a mutation—
all of which can tend to be computationally expensive. A virtual DOM won’t get you
around this, but it can help updates to the DOM be optimized to account for these
constraints.
When creating and managing a sizeable application that deals with data that
changes over time, many changes to the DOM may be required, and often these
changes can conflict or are done in a less-than-optimal way. That can result in an
overly complicated system that’s difficult for engineers to work on and likely a subpar
experience for users—lose-lose. Thus performance is another key consideration in
React’s design and implementation. Implementing a virtual DOM helps address this,
but it should be noted that it’s designed to be just “fast enough.” A robust API, simple
mental model, and other things like cross-browser compatibility end up being more
important outcomes of React’s virtual DOM than an extreme focus on performance.
The reason I make this point is that you may hear the virtual DOM talked about as a
sort of silver bullet for performance. It is performant, but it’s no magic performance
bullet, and at the end of the day, many of its other benefits are more important for
working with React.
Licensed to Samir Mashlum <smashlum@gmail.com>
45. 16 CHAPTER 1 Meet React
1.3.3 Updates and diffing
How does the virtual DOM work? React’s virtual DOM has a few similarities to another
software world: 3D gaming. 3D games sometimes employ a rendering process that
works very roughly as follows: get information from the game server, send it to the
game world (the visual representation that the user sees), determine what changes
need to be made to the visual world, and then let the graphics card determine the
minimum changes necessary. One advantage of this approach is that you only need
the resources for dealing with incremental changes and can generally do things much
quicker than if you had to update everything.
That’s a gross oversimplification of the way 3D games are rendered and updated,
but the general ideas give us a good example to think of when looking at how React
performs updates. DOM mutation done poorly can be expensive, so React tries to be
efficient in its updates to your UI and employs methods similar to 3D games.
As figure 1.5 shows, React creates and maintains a virtual DOM in memory, and a
renderer like React-DOM handles updating the browser DOM based on changes.
React can perform intelligent updates and only do work on parts that have changed
because it can use heuristic diffing to calculate which parts of the in-memory DOM
require changes to the DOM. Theoretically, this is much more streamlined and ele-
gant than “dirty checking” or other more brute-force approaches, but a major practi-
cal implication is that developers have less complicated state tracking to reason about.
Real DOM
Updated DOM
Diff Patch
In-memory DOM
Model
Figure 1.5 React’s diffing and update procedure. When a change happens, React
determines differences between the actual and in-memory DOMs. Then it performs an
efficient update to the browser’s DOM. This process is often referred to as a diff (“what
changed?”) and patch (“update only what changed”) process.
Licensed to Samir Mashlum <smashlum@gmail.com>
46. 17
Components: The fundamental unit of React
1.3.4 Virtual DOM: Need for speed?
As I’ve noted, there’s more to the virtual DOM than speed. It’s performant by design
and generally results in snappy, speedy applications that are fast enough for modern
web application needs. Performance and a better mental model have been so appreci-
ated by engineers that many popular JavaScript libraries are creating their own ver-
sions or variations of a virtual DOM. Even in these cases, people tend to think that the
virtual DOM is primarily focused on performance. Performance is a key feature of
React, but it’s secondary to simplicity. The virtual DOM is part of what enables you to
defer thinking about complicated state logic and focus on other, more important
parts of your application. Together, speed and simplicity mean happier users and hap-
pier developers—a win-win!
I’ve spent some time talking about the virtual DOM, but I don’t want to give you the
idea that it will be an important part of working with React. In practice, you won’t need
to be thinking extensively about how the virtual DOM is accomplishing your data
updates or making your changes to your application. That’s part of the simplicity of
React: you’re freed up to focus on the parts of your application that need the most focus.
1.4 Components: The fundamental unit of React
React doesn’t just use a novel approach to dealing with changing data over time; it
also focuses on components as a paradigm for organizing your application. Compo-
nents are the most fundamental unit of React. There are several different ways you
can create components with React, which future chapters will cover. Thinking in
terms of components is essential for grasping not only how React was meant to work
but also how you can best use it in your projects.
1.4.1 Components in general
What is a component? It’s a part of a larger whole. The idea of components is likely
familiar to you, and you probably see them often even though you might not realize it.
Using components as mental and visual tools when designing and building user inter-
faces can lead to better, more intuitive application design and use. A component can
be whatever you determine it to be, although not everything makes sense as a compo-
nent. For example, if you decide that the entirety of an interface is a component, with
no child components or further subdivisions, you’re probably not helping yourself.
Instead, it’s helpful to break different parts of an interface into parts that can be com-
posed, reused, and easily reorganized.
To start thinking in terms of components, we’ll look at an example interface and
break it down into its constituent parts. Figure 1.6 shows an example of an interface
you’ll be working on later in the book. User interfaces often contain elements that are
reused or repurposed in other parts of the interface. And even if they’re not reused,
they’re at least distinct. These different elements, the distinct elements of an inter-
face, can be thought of as components. The interface on the left in figure 1.6 is bro-
ken down into components on the right.
Licensed to Samir Mashlum <smashlum@gmail.com>
47. 18 CHAPTER 1 Meet React
1.4.2 Components in React: Encapsulated and reusable
React components are well encapsulated, reusable, and composable. These character-
istics help enable a simpler and more elegant way of thinking about and building user
interfaces. Your application can be comprised of clear, concise groups instead of
being a spaghetti-code mess. Using React to build your application is almost like
Exercise 1.1 Component thinking
Visit a popular site that you enjoy and use often (like GitHub, for example) and break
down the interface into components. As you go, you’ll probably find yourself dividing
things into separate parts. When does it make sense to stop breaking things down?
Should an individual letter be a component? When might it make sense for a compo-
nent to be something small? When would it make sense to consider a grouping of
things as one component?
David commented
SJ was too mainstream for me.
Peter commented
Who was Samuel Johnson?
Peter commented
Mitchell commented
"
@Peter get off Letters and do your homework!
What we hope ever to do with ease, we must
first learn to do with diligence.
— Samuel Johnson
Mark posted 4 comments
Comment
Haley & Annmarie like this
Comment here…
Letters |Social
@mitchell ok dad :P
Comment-box Component
Post Component
Comment Component
Create Comment Component
Figure 1.6 An example of an interface broken into components. Each distinct section can be thought of as a
component. Items that repeat in a uniform nature can be thought of as one component that gets reused over
different data.
Licensed to Samir Mashlum <smashlum@gmail.com>
48. 19
React for teams
building your project with LEGOs, except that you can’t run out of pieces. You’ll
encounter bugs, but thankfully there are no pieces to step on.
In exercise 1.1, you practiced thinking with components and broke an interface
into some constituent components. You could have done it any number of ways, and
it’s possible you might not have been especially organized or consistent. That’s fine.
But when you work with components in React, it will be important to consider orga-
nization and consistency in component design. You’ll want to design components
that are self-contained and focus on a particular concern or a handful of related
concerns.
This lends itself towards components that are portable, logically grouped, and easy
to move around and reuse throughout your application. Even if it takes advantage of
other libraries, a well-designed React component should be fairly self-contained.
Breaking your UI into components allows you to work more easily on different parts
of the application. Boundaries between components mean that functionality and
organization can be well-defined, whereas self-contained components mean they can
be reused and moved around more easily.
Components in React are meant to work together. This means you can compose
together components to form new composite components. Component composition is
one of the most powerful aspects of React. You can create a component once and
make it available to the rest of your application for reuse. This is often especially help-
ful in larger applications. If you’re on a medium-to-large team, you could publish
components to a private registry (npm or otherwise) that other teams could easily pull
down and use in new or existing projects. This might not be a realistic scenario for all
sizes of teams, but even smaller teams will benefit from the code reuse that React com-
ponents promote.
A final aspect of React components is lifecycle methods. These are predictable, well-
defined methods you can use as your component moves through different parts of its
lifecycle (mounting, updating, unmounting, and so on). We’ll spend a lot of time on
these methods in future chapters.
1.5 React for teams
You now know a little bit more about components in React. React can make your life
easier as an individual developer. But what about on a team? Overall, what makes
React so appealing to individual developers is also what can make it a great fit for
teams. Like any technology, React isn’t a perfect solution for every use case or project,
no matter the hype or what fanatical developers may try to convince you of. As you’ve
already seen, there are many things that React doesn’t do. But the things it does do, it
does extremely well.
What makes React a great tool for larger teams and larger applications? First,
there’s the simplicity of using it. Simplicity is not the same thing as ease. Easy solutions
are often dirty and quick, and worst of all, they can incur technical debt. Truly simple
technology is flexible and robust. React provides powerful abstractions that can still
Licensed to Samir Mashlum <smashlum@gmail.com>
49. 20 CHAPTER 1 Meet React
be worked with along with ways to drop down into the lower-level details when neces-
sary. Simple technology is easier to understand and work with because the difficult
work of streamlining and removing what’s not necessary has been done. In many ways
React has made simple easy, providing an effective solution without introducing harm-
ful “black magic” or an opaque API.
All this is great for the individual developer, but the effect is amplified across larger
teams and organizations. Although there’s certainly room for React to improve and
keep growing, the hard work of making it a simple and flexible technology pays off for
engineering teams. Simpler technologies with good mental models tend to create less
of a mental burden for engineers and let them move faster and have a higher impact.
As a bonus, a simpler set of tools is easier to learn for new employees. Trying to ramp
up a new team member to an overly complex stack will not only cost time for the train-
ing engineers, it will also probably mean that the new developer will be unable to
make meaningful contributions for some time. Because React seeks to carefully rethink
established best practices, there’s the initial cost in paradigm switch, but after that it’s
often a big, long-term win.
Although it’s certainly a different tool than others in the same space, React is a
fairly lightweight library in terms of responsibility and functionality. Where something
like Angular may require you to “buy in” to a more comprehensive API, React is only
concerned with the view of your application. This means it’s much more trivial to inte-
grate it with your current technologies, and it will leave you room to make choices
about other aspects. Some opinionated frameworks and libraries require an all-or-
nothing adoption stance, but React’s “just the view” scope and general interoperabil-
ity with JavaScript mean this isn’t always the case.
Instead of going all-in, you can incrementally transition different projects or tools
over to React without having to make a drastic change to your structure, build stack,
or other related areas. That’s a desirable trait for almost any technology, and it’s how
React was first tried out at Facebook—in one small project area. From there it grew
and took hold as more and more teams saw and experienced its benefits. What does
all this mean for your team? It means you can evaluate React without having to take
the risk of completely rewriting the product using React.
The simplicity, un-opinionated nature, and performance of React make it a great
fit for projects small and large alike. As you keep exploring React, you’ll see how it can
be a good fit for your team and projects.
1.6 Summary
React is a library for creating user interfaces that was initially built and open
sourced by Facebook. It’s a JavaScript library built with simplicity, performance, and
components in mind. Rather than provide a comprehensive set of tools for creating
applications, it allows you to choose how to implement your data models, server
calls, and other application concerns, and what to implement them with. These key
reasons and others are why React can be a great tool for small and large applications
Licensed to Samir Mashlum <smashlum@gmail.com>
51. of grapes that grew in a cemetery; the second, that the lamb was
brought up on dog’s milk; while the third asserts that the emperor
had put to death the son of the wazír, and that the latter is bent on
vengeance. All these statements turn out to be well-grounded. Mr.
Tawney also refers to parallel stories in the Breslau edition of The
Nights; namely, in Night 458, it is similarly conjectured that the
bread was baked by a sick woman; that the kid was suckled by a
bitch, and that the sultan is illegitimate; and in Night 459, a gem-
cutter guesses that a jewel has an internal flaw, a man skilled in the
pedigrees of horses divines that a horse is the offspring of a female
buffalo, and a man skilled in human pedigrees that the mother of
the favourite queen was a rope-dancer. Similar incidents occur in
“The Sultan of Yemen and his Three Sons,” one of the Additional
Tales translated by Scott, from the Wortley-Montague MS., now in
the Bodleian Library, and comprised in vol. vi. of his edition of “The
Arabian Nights Entertainments,” published at London in 1811.
An analogous tale occurs in Mr. E. J. W. Gibb’s recently-published
translation of the “History of the Forty Vezírs” (the Lady’s Fourth
Story, p. 69 ff.), the motif of which is that “all things return to their
origin.”
TURKISH ANALOGUE.
There was in the palace of the world a king who was very desirous
of seeing Khizr[504]
(peace on him!), and he would even say, “If there
be any one who will show me Khizr, I will give him whatsoever he
may wish.” Now there was at that time a man poor of estate, and
from the stress of his poverty he said to himself, “Let me go and
speak to the king, that if he provide for me during three years,
either I shall be dead, or the king will be dead, or he will forgive me
my fault, or I shall on somewise win to escape, and in this way shall
I make merry for a time.” So he went to the king and spake these
words to him.[505]
The king said, “An thou show him not, then I will
52. kill thee,” and that poor man consented. Then the king let give him
much wealth and money, and the poor man took that wealth and
money and went to his house. Three years he spent in merriment
and delight, and he rested at ease till the term was accomplished. At
the end of that time he fled and hid himself in a trackless place and
he began to quake for fear. Of a sudden he saw a personage with
white raiment and shining face, who saluted him. The poor man
returned the salutation, and the radiant being asked, “Why art thou
thus sad?” But he gave no answer. Again the radiant being asked
him and sware to him, saying, “Do indeed tell to me thy plight, that I
may find thee some remedy.” So that hapless one narrated his story
from its beginning to its end, and the radiant being said, “Come, I
will go with thee to the king, and I will answer for thee.” So they
arose.
Now the king wanted that hapless one, and while they were going
some of the king’s officers who were seeking met them, and they
straightway seized the poor man and brought him to the king. Quoth
the king, “Lo, the three years are accomplished; come now, and
show me Khizr.” The poor man said, “My king, grace and bounty are
the work of kings—forgive my sin.” Quoth the king, “I made a pact;
till I have killed thee, I shall not have fulfilled it.” And he looked to
his chief vezír and said, “How should this be done?” Quoth the vezír,
“This man should be hewn in many pieces and then hung up on
butchers’ hooks, that others may see and lie not before the king.”
Said that radiant being, “True spake the vezír;—all things return to
their origin.” Then the king looked to the second vezír and said,
“What sayest thou?” He replied, “This man should be boiled in a
cauldron.” Said that radiant being, “True spake the vezír;—all things
return to their origin.” The king looked to the third vezír and said,
“What sayest thou?” The vezír replied, “This man should be hewn in
small pieces and baked in an oven.” Again said that elder, “True
spake the vezír;—all things return to their origin.” Then quoth the
king to the fourth vezír, “Let us see what sayest thou?” The vezír
replied, “O king, the wealth thou gavest this poor creature was for
the love of Khizr (peace on him!) He, thinking to find him, accepted
53. it; now that he has not found him he seeks pardon. This were
befitting, that thou set free this poor creature for the love of Khizr.”
Said that elder, “True spake the vezír;—all things return to their
origin.” Then the king said to the elder, “O elder, my vezírs have said
different things contrary the one to the other, and thou hast said
concerning each of them, ‘True spake the vezír;—all things return to
their origin.’ What is the reason thereof?” That elder replied, “O king,
thy first vezír is a butcher’s son; therefore did he draw to his origin.
Thy second vezír is a cook’s son, and he likewise proposed a
punishment as became his origin. Thy third vezír is a baker’s son; he
likewise proposed a punishment as became his origin. But thy fourth
vezír is of gentle birth; compassion therefore becomes his origin, so
he had compassion on that hapless one, and sought to do good and
counselled liberation. O king, all things return to their origin.”[506]
And
he gave the king much counsel, and at last said, “Lo, I am Khizr,”
and vanished.[507]
The discovery of the king’s illegitimate birth, which occurs in so
many versions, has its parallels in the story of the Nephew of
Hippocrates in the “Seven Wise Masters,” and the Lady’s 2nd Story in
Mr. Gibb’s translation of the “Forty Vezírs.” The extraordinary
sensitiveness of the third young Bráhman, in the Vetála story, whose
side was scratched by a hair that was under the seventh of the
mattresses on which he lay, Rohde (says Tawney), in his
“Greichische Novellistik,” p. 62, compares with a story told by Aelian
of the Sybarite Smindyrides, who slept on a bed of rose-leaves and
got up in the morning covered with blisters. He also quotes from the
Chronicle of Tabari a story of a princess who was made to bleed by a
rose-leaf lying in her bed.[508]
The eleventh recital of the Vetála is about a king’s three sensitive
wives: As one of the queens was playfully pulling the hair of the
king, a blue lotus leaped from her ear and fell on her lap;
immediately a wound was produced on the front of her thigh by the
blow, and the delicate princess exclaimed “Oh! oh!” and fainted. At
54. night, the second retired with the king to an apartment on the roof
of the palace exposed to the rays of the moon, which fell on the
body of the queen, who was sleeping by the king’s side, where it
was exposed by her garment blowing aside; immediately she woke
up, exclaiming, “Alas! I am burnt,” and rose up from the bed rubbing
her limbs. The king woke up in a state of alarm, crying out, “What is
the meaning of this?” Then he got up and saw that blisters had been
produced on the queen’s body. In the meanwhile the king’s third
wife heard of it and left her palace to come to him. And when she
got into the open air, she heard distinctly, as the night was still, the
sound of a pestle pounding in a distant house. The moment the
gazelle-eyed one heard it, she said “Alas! I am killed,” and she sat
down on the path, shaking her hands in an agony of pain. Then the
girl turned back, and was conducted by her attendants to her own
chamber, where she fell on her bed and groaned. And when her
weeping attendants examined her, they saw that her hands were
covered with bruises, and looked like lotuses upon which black
beetles had settled.
To this piteous tale of the three very sensitive queens Tawney
appends the following note: Rohde, in his “Greichische Novellistik,”
p. 62, compares with this a story told by Timæus, of a Sybarite who
saw a husbandman hoeing a field, and contracted rupture from it.
Another Sybarite, to whom he told the tale of his sad mishap, got
ear-ache from hearing it. Oesterley, in his German translation of the
Baitál Pachísí, points out that Grimm, in his “Kindermärchen,” iii. p.
238, quotes a similar incident from the travels of the Three Sons of
Giaffar: out of four princesses, one faints because a rose-twig is
thrown into her face among some roses; a second shuts her eyes in
order not to see the statue of a man; a third says, “Go away; the
hairs in your fur cloak run into me;” and the fourth covers her face,
fearing that some of the fish in a tank may belong to the male sex.
He also quotes a striking parallel from the “Elites des contes du Sieur
d’Onville:” Four ladies dispute as to which of them is the most
delicate. One has been lame for three months owing to a rose-leaf
having fallen on her foot; another has had three ribs broken by a
55. sheet in her bed having been crumpled; a third has held her head on
one side for six weeks owing to one half of her head having three or
more hairs on it than the other; a fourth has broken a blood-vessel
by a slight movement, and the rupture cannot be healed without
breaking the whole limb. [Poor things!]
56. THE PRINCE WHO FELL IN LOVE WITH THE
PICTURE. Vol. I. p. 226.
In the Persian tales of “The Thousand and One Days,” a young
prince entered his father’s treasury one day, and saw there a little
cedar chest “set with pearls, diamonds, emeralds, and topazes;” on
opening it (for the key was in the lock) he beheld the picture of an
exceedingly beautiful woman, with whom he immediately fell in love.
Ascertaining the name of the lady from an inscription on the back of
the portrait, he sets off with a companion to discover her, and
having been told by an old man at Baghdád that her father at one
time reigned in Ceylon, he continued his journey thither,
encountering many unheard-of adventures by the way. Ultimately he
is informed that the lady with whose portrait he had become
enamoured was one of the favourites of King Solomon. One should
suppose that this would have effectually cured the love-sick prince;
but no: he “could never banish her sweet image from his heart.”[509]
Two instances of falling in love with the picture of a pretty woman
occur in the “Kathá Sarít Ságara.” In Book ix., chap. 51, a painter
shows King Prithvirúpa the “counterfeit presentment” of the
beauteous Princess Rapalatá, and “as the king gazed on it his eye
was drowned in that sea of beauty her person, so that he could not
draw it out again. For the king, whose longing was excessive, could
not be satisfied with devouring her form, which poured forth a
stream of the nectar of beauty, as the partridge cannot be satisfied
with devouring the moonlight.” In Book xii., chap. 100, a female
ascetic shows a wandering prince the portrait of the Princess
Mandáravatí, “and Sundarasena when he beheld that maiden, who,
though she was present there only in a picture, seemed to be of
romantic beauty and like a flowing forth of joy, immediately felt as if
he had been pierced with the arrows of the god of the flowery bow
[i.e. Káma].” In chapter 35 of Scott’s translation of the “Bahár-i-
57. Dánish,” Prince Ferokh-Faul opens a volume, “which he had scarcely
done when the fatal portrait of the fair princess who, the astrologers
had foretold, was to occasion him so many perils, presented itself to
his view. He instantly fainted, when the slave, alarmed, conveyed
intelligence of his condition to the sultan, and related the unhappy
cause of the disorder.” In Gomberville’s romance of Polexandre, the
African prince, Abd-el-Malik, falls in love with the portrait of
Alcidiana, and similar incidents occur in the romance of Agesilaus of
Colchos and in the Story of the Seven Wazírs (vol. vi.); but why
multiply instances? Nothing is more common in Asiatic fictions.
58. THE FULLER, HIS WIFE, AND THE TROOPER.
Vol. I. p. 231.
In addition to the versions of this amusing story referred to on p.
231—all of which will be found in the second volume of my work on
“Popular Tales and Fictions,” pp. 212–228—there is yet another in a
Persian story-book, of unknown date, entitled “Shamsa ú Kuhkuha,”
written by Mirza Berkhorder Turkman, of which an account, together
with specimens, is given in a recently-published little book
(Quaritch), “Persian Portraits: a sketch of Persian History, Literature,
and Politics,” by Mr. F. F. Arbuthnot, author of “Early Ideas: a Group
of Hindoo Stories.”
This version occurs in a tale of three artful wives—or, to employ the
story-teller’s own graphic terms, “three whales of the sea of fraud
and deceit: three dragons of the nature of thunder and the
quickness of lightning; three defamers of honour and reputation;
namely, three men-deceiving, lascivious women, each of whom had
from the chicanery of her cunning issued the diploma of turmoil to a
hundred cities and countries, and in the arts of fraud they accounted
Satan as an admiring spectator in the theatre of their stratagems.[510]
One of them was sitting in the court of justice of the kazi’s embrace;
the second was the precious gem of the bazaar-master’s diadem of
compliance; and the third was the beazle and ornament of the
signet-ring of the life and soul of the superintendent of police. They
were constantly entrapping the fawns of the prairie of deceit within
the grasp of cunning, and plundered the wares of the caravan of
tranquillity of hearts of strangers and acquaintances, by means of
the edge of the scimitar of fraud. One day this trefoil of roguery met
at the public bath, and, according to their homogeneous nature they
intermingled as intimately as the comb with the hair; they tucked up
their garment of amity to the waist of union, entered the tank of
agreement, seated themselves in the hot-house of love, and poured
59. from the dish of folly, by means of the key of hypocrisy, the water of
profusion upon the head of intercourse; they rubbed with the brush
of familiarity and the soap of affection the stains of jealousies from
each other’s limbs. After a while, when they had brought the pot of
concord to boil by the fire of mutual laudation, they warmed the
bath of association with the breeze of kindness, and came out. In
the dressing-room all three of them happened simultaneously to find
a ring, the gem of which surpassed the imagination of the jeweller
of destiny, and the like of which he had never beheld in the
storehouse of possibility. In short, these worthy ladies contended
with each other for possession of the ring, until at length the mother
of the bathman came forward and proposed that they should entrust
the ring to her in the meanwhile, and it should be the prize of the
one who most cleverly deceived and befooled her husband, to which
they all agreed, and then departed for their respective domiciles.”[511]
Mr. Arbuthnot’s limits permitted only of abstracts of the tricks played
upon their husbands by the three ladies—which the story-teller gives
at great length—and that of the kazi’s wife is as follows:
The kazi’s wife knows that a certain carpenter, who lived close to
her, was very much in love with her. She sends her maid to him with
a message to say that the flame of his love had taken effect upon
her heart, and that he must make an underground passage between
his house and her dwelling, so that they might communicate with
each other freely by means of the mine. The carpenter digs the
passage, and the lady pays him a visit, and says to him, “To-morrow
I shall come here, and you must bring the kazi to marry me to you.”
The next day the kazi goes to his office; the lady goes to the
carpenter’s house, and sends him to bring her husband, the kazi, to
marry them. The carpenter fetches him, and, as the kazi hopes for a
good present, he comes willingly enough, but is much surprised at
the extreme likeness between the bride and his own wife. The more
he looks at her, the more he is in doubt; and at last, offering an
excuse to fetch something, he rushes off to his own house, but is
forestalled by his spouse, who had gone thither by the passage, and
on his arrival is lying on her bed. The kazi makes some excuses for
60. his sudden entry into her room, and, after some words, goes back to
the carpenter’s house; but his wife had preceded him, and is sitting
in her place. Again he begins the ceremony, but is attracted by a
black mole on the corner of the bride’s lip, which he could have
sworn was the same as that possessed by his wife. Making more
excuses, and in spite of the remonstrances of the carpenter, he
hurries back to his house once more; but his wife had again got
there before him, and he finds her reading a book, and much
astonished at his second visit. She suggests that he is mad, and he
admits that his conduct is curious, and returns to the carpenter’s
house to complete the ceremony. This is again frequently
interrupted, but finally he marries his own wife to the carpenter, and,
having behaved in such an extraordinary manner throughout, is sent
off to a lunatic asylum.
For the tricks of the two other ladies, and for many other equally
diverting tales, I refer the reader to Mr. Arbuthnot’s pleasing and
instructive little book, which is indeed an admirable epitome of the
history and literature of Persia, and one which was greatly wanted in
these days, when most men, “like the dogs in Egypt for fear of the
crocodiles, must drink of the waters of information as they run, in
dread of the old enemy Time.”
I have discussed the question of the genealogy of this tale
elsewhere, but, after a somewhat more minute comparative analysis
of the several versions, am disposed to modify the opinion which I
then entertained. I think we must consider as the direct or indirect
source of the versions and variants the “Miles Gloriosus” of Plautus,
the plot of which, it is stated in the prologue to the second act, was
taken from a Greek play. It is, however, not very clear whether Berni
adapted his story from Plautus or the “Seven Wise Masters”;
probably from the former, since in both the lady is represented, to
the captain and the cuckold, as a twin sister, while in the S. W. M.
the crafty knight pretends that she is his leman, come from Hungary
with tidings that he may now with safety return home. On the other
hand, in the S. W. M., as in Plautus, the lovers make their escape by
61. sea, an incident which Berni has altered to a journey by land—no
doubt, in order to introduce further adventures for the development
of his main plot. But then we find a point of resemblance between
Berni and the S. W. M., in the incident of the cuckold accompanying
the lovers part of their way—in the latter to the sea-shore; while in
Plautus the deceived captain remains at home to prosecute an
amour and get a thrashing for his reward (in Plautus, instead of a
wife, it is the captain’s slave-girl). It is curious that amidst all the
masquerade of the Arabian story the cuckold’s wife also personates
her supposititious twin-sister, as in Plautus and Berni. In Plautus the
houses of the lover and the captain adjoin, as is also the case in the
modern Italian and Sicilian versions; while in Berni, the S. W. M., the
Arabian, and the Persian story cited in this note they are at some
distance. With these resemblances and variations it is not easy to
say which version was derived from another. Evidently the Arabian
story has been deliberately modified by the compiler, and he has, I
think, considerably improved upon the original: the ludicrous
perplexity of the poor fuller when he awakes, to find himself
apparently transformed into a Turkish trooper, recalls the nursery
rhyme of the little woman “who went to market her eggs for to sell,”
and falling asleep on the king’s highway, a pedlar cut off her
petticoats up to the knees, and when she awoke and saw her
condition she exclaimed, “Lawk-a-mercy me, this is none of I!” and
so on. And not less diverting is the pelting the blockhead receives
from his brother fullers—altogether, a capital story.
62. TALE OF THE SIMPLETON HUSBAND.—Vol. I. p.
239.
The “curious” reader will find European and Asiatic versions of this
amusing story in “Originals and Analogues of some of Chaucer’s
Canterbury Tales,” published for the Chaucer Society, pp. 177–188
and (in a paper contributed by me: “The Enchanted Tree”) p. 341–
364.
63. TALE OF THE THREE MEN AND OUR LORD ISA.
Vol. I. p. 250.
Under the title of “The Robbers and the Treasure-Trove” I have
brought together many European and Asiatic versions of this wide-
spread tale in “Chaucer Analogues,” pp. 415–436.
64. THE MELANCHOLIST AND THE SHARPER. Vol.
I. p. 264.
A similar but much shorter story is found in Gladwin’s “Persian
Moonshee,” and story-books in several of the Indian vernaculars
which have been rendered into English:
A miser said to a friend, “I have now a thousand rupees, which I will
bury out of the city, and I will not tell the secret to any one besides
yourself.” They went out of the city together, and buried the money
under a tree. Some days after the miser went alone to the tree and
found no signs of his money. He said to himself, “Excepting that
friend, no other has taken it away; but if I question him he will never
confess.” He therefore went to his (the friend’s) house and said, “A
great deal of money is come into my hands, which I want to put in
the same place; if you will come to-morrow, we will go together.”
The friend, by coveting this large sum, replaced the former money,
and the miser next day went there alone and found it. He was
delighted with his own contrivance, and never again placed any
confidence in friends.
One should suppose a miser the last person to confide the secret of
his wealth to any one; but the Italian versions bear a closer
resemblance to the Arabian story. From No. 74 of the “Cento Novelle
Antiche” Sacchetti, who was born in 1335 and is ranked by
Crescimbini as next to Boccaccio, adapted his 198th novella, which is
a most pleasing version of the Asiatic story:
ITALIAN VERSION.
A blind man of Orvieto, of the name of Cola, hit upon a device to
recover a hundred florins he had been cheated of, which showed he
65. was possessed of all the eyes of Argus, though he had unluckily lost
his own. And this he did without wasting a farthing either upon law
or arbitration, by sheer dexterity; for he had formerly been a barber,
and accustomed to shave very close, having then all his eyes about
him, which had been now closed for about thirty years. Alms seemed
then the only resource to which he could betake himself, and such
was the surprising progress he in a short time made in his new trade
that he counted a hundred florins in his purse, which he secretly
carried about him until he could find a safer place. His gains far
surpassed anything he had realised with his razor and scissors;
indeed, they increased so fast that he no longer knew where to
bestow them; until one morning happening to remain the last, as he
believed, in the church, he thought of depositing his purse of a
hundred florins under a loose tile in the floor behind the door,
knowing the situation of the place perfectly well. After listening
some time without hearing a foot stirring, he very cautiously laid it in
the spot; but unluckily there remained a certain Juccio
Pezzichernolo, offering his adoration before an image of San
Giovanni Boccadoro, who happened to see Cola busily engaged
behind the door. He continued his adorations until he saw the blind
man depart, when, not in the least suspecting the truth, he
approached and searched the place. He soon found the identical tile,
and on removing it with the help of his knife, he found the purse,
which he very quietly put into his pocket, replacing the tiles just as
they were, and, resolving to say nothing about it, he went home.
At the end of three days the blind mendicant, desirous of inspecting
his treasure, took a quiet time for visiting the place, and removing
the tile searched a long while in great perturbation, but all in vain, to
find his beloved purse. At last, replacing things just as they were, he
was compelled to return in no very enviable state of mind to his
dwelling; and there meditating on his loss, the harvest of the toil of
so many days, by dint of intense thinking a bright thought struck
him (as frequently happens by cogitating in the dark), how he had
yet a kind of chance of redeeming his lost spoils. Accordingly in the
morning he called his young guide, a lad about nine years old,
66. saying, “My son, lead me to church,” and before setting out he
tutored him how he was to behave, seating himself at his side
before the entrance, and particularly remarking every person who
should enter into the church. “Now, if you happen to see any one
who takes particular notice of me, and who either laughs or makes
any sign, be sure you observe it and tell me.” The boy promised he
would; and they proceeded accordingly and took their station before
the church.
When the dinner-hour arrived, the father and son prepared to leave
the place, the former inquiring by the way whether his son had
observed any one looking hard at him as he passed along. “That I
did,” answered the lad, “but only one, and he laughed as he went
past us. I do not know his name, but he is strongly marked with the
small-pox and lives somewhere near the Frati Minori.” “Do you think,
my dear lad,” said his father, “that you could take me to his shop,
and tell me when you see him there?” “To be sure I could,” said the
lad. “Then come, let us lose no time,” replied the father; “and when
we are there tell me, and while I speak to him you can step on one
side and wait for me.” So the sharp little fellow led him along the
way until he reached a cheesemonger’s stall, when he acquainted
his father, and brought him close to it. No sooner did the blind man
hear him speaking with his customers than he recognised him for
the same Juccio with whom he had formerly been acquainted during
his days of light. When the coast was a little clear, our blind hero
entreated some moments’ conversation, and Juccio, half suspecting
the occasion, took him on one side into a little room, saying, “Cola,
friend, what good news?” “Why,” said Cola, “I am come to consult
you, in great hopes you will be of use to me. You know it is a long
time since I lost my sight, and being in a destitute condition, I was
compelled to earn my subsistence by begging alms. Now, by the
grace of God, and with the help of you and of other good people of
Orvieto, I have saved a sum of two hundred florins, one hundred of
which I have deposited in a safe place, and the other is in the hands
of my relations, which I expect to receive with interest in the course
of a week. Now if you would consent to receive, and to employ for
67. me to the best advantage, the whole sum of two hundred florins, it
would be doing me a great kindness, for there is no one besides in
all Orvieto in whom I dare to confide; nor do I like to be at the
expense of paying a notary for doing business which we can as well
transact ourselves. Only I wish you would say nothing about it, but
receive the two hundred florins from me to employ as you think
best. Say not a word about it, for there would be an end of my
calling were it known I had received so large a sum in alms.” Here
the blind mendicant stopped; and the sly Juccio, imagining he might
thus become master of the entire sum, said he should be very happy
to serve him in every way he could, and would return an answer the
next morning as to the best way of laying out the money. Cola then
took his leave, while Juccio, going directly for the purse, deposited it
in its old place being in full expectation of soon receiving it again
with the addition of the other hundred, as it was clear that Cola had
not yet missed the money. The cunning old mendicant on his part
expected that he would do no less, and trusting that his plot might
have succeeded, he set out the very same day to the church, and
had the delight, on removing the tile, to find his purse really there.
Seizing upon it with the utmost eagerness, he concealed it under his
clothes, and placing the tiles exactly in the same position, he
hastened home whistling, troubling himself very little about his
appointment of the next day.
The sly thief Juccio set out accordingly the next morning to see his
friend Cola, and actually met him on the road. “Whither are you
going?” inquired Juccio. “I was going,” said Cola, “to your house.”
The former, then taking the blind man aside, said, “I am resolved to
do what you ask; and since you are pleased to confide in me, I will
tell you of a plan that I have in hand for laying out your money to
advantage. If you will put the two hundred florins into my
possession, I will make a purchase in cheese and salt meat, a
speculation which cannot fail to turn to good account.” “Thank you,”
quoth Cola, “I am going to-day for the other hundred, which I mean
to bring, and when you have got them both, you can do with them
what you think proper.” Juccio said, “Then let me have them soon,
68. for I think I can secure this bargain; and as the soldiers are come
into the town, who are fond of these articles, I think it cannot fail to
answer; so go, and Heaven speed you.” And Cola went; but with
very different intentions from those imagined by his friend—Cola
being now clear-sighted, and Juccio truly blind. The next day Cola
called on his friend with very downcast and melancholy looks, and
when Juccio bade him good day, he said, “I wish from my soul it
were a good, or even a middling, day for me.” “Why, what is the
matter?” “The matter?” echoed Cola; “why, it is all over with me;
some rascal has stolen a hundred florins from the place where they
were hidden, and I cannot recover a penny from my relations, so
that I may eat my fingers off for anything I have to expect.” Juccio
replied, “This is like all the rest of my speculations. I have invariably
lost where I expected to make a good hit. What I shall do I know
not; for if the person should choose to keep me to the agreement I
made for you, I shall be in a pretty dilemma indeed.” “Yet,” said
Cola, “I think my condition is still worse than yours. I shall be sadly
distressed, and shall have to amass a fresh capital, which will take
me ever so long. And when I have got it, I will take care not to
conceal it in a hole in the floor, or trust it, Juccio, into any friend’s
hands.” “But,” said Juccio, “if we could contrive to recover what is
owing by your relations, we might still make some pretty profit of it,
I doubt not.” For he thought, if he could only get hold of the
hundred he had returned it would still be something in his way.
“Why,” said Cola, “to tell the truth, if I were to proceed against my
relations, I believe I might get it; but such a thing would ruin my
business, my dear Juccio, for ever: the world would know I was
worth money, and I should get no more money from the world; so I
fear I shall hardly be able to profit by your kindness, though I shall
always consider myself as much obliged as if I had actually cleared a
large sum. Moreover, I am going to teach another blind man my
profession, and if we have luck you shall see me again, and we can
venture a speculation together.” So far the wily mendicant, to whom
Juccio said, “Well, go and try to get money soon, and bring it; you
know where to find me, but look sharp about you and the Lord
speed you; farewell.” “Farewell,” said Cola; “and I am well rid of
69. thee,” he whispered to himself; and going upon his way, in a short
time he doubled his capital; but he no longer went near his friend
Juccio to know how he should invest it. He had great diversion in
telling the story to his companions during their feasts, always
concluding, “By St. Lucia! Juccio is the blinder man of the two: he
thought it was a bold stroke to risk his hundred to double the
amount.”
For my own part, I think the blind must possess a more acute
intellect than other people, inasmuch as the light, exhibiting such a
variety of objects to view, is apt to distract the attention, of which
many examples might be adduced. For instance, two gentlemen may
be conversing together on some matter of business, and in the
middle of a sentence a fine woman happens to pass by, and they will
suddenly stop, gazing after her; or a fine equipage, or any other
object is enough to turn the current of their thoughts. And then we
are obliged to recollect ourselves, saying, “Where was I?” “What was
it that I was observing?”—a thing which never occurs to a blind man.
The philosopher Democritus very properly on this account knocked
his eyes out in order to catch objects in a juster light with his mind’s
eye.
It is impossible to describe Juccio’s vexation on going to church and
finding the florins were gone. His regret was far greater than if he
had actually lost a hundred of his own; as is known to be the case
with all inveterate rogues, half of whose pleasure consists in
depriving others of their lawful property.
There are many analogous stories, one of which is the well-known
tale of the merchant, who, before going on a journey, deposited with
a dervish 1,000 sequins, which he thought it prudent to reserve in
case of accidents. When he returned and requested his deposit, the
dervish flatly denied that he ever had any of his money. Upon this
the merchant went and laid his case before the kazi, who advised
him to return to the dervish and speak pleasantly to him, which he
does, but receives nothing but abuse. He informed the kazi of this,
70. and was told not to go near the dervish for the present, but to be at
ease for he should have his money next day. The kazi then sent for
the dervish, and after entertaining him sumptuously, told him that,
for certain reasons, he was desirous of removing a considerable sum
of money from his house; that he knew of no person in whom he
could confide so much as himself; and that if he would come the
following evening at a late hour, he should have the precious
deposit. On hearing this, the dervish expressed his gratification that
so much confidence should be placed in his integrity, and agreed to
take charge of the treasure. Next day the merchant returned to the
kazi, who bade him go back to the dervish and demand his money
once more, and should he refuse, threaten to complain to the kazi.
The result may be readily guessed: no sooner did the merchant
mention the kazi than the rascally dervish said, “My good friend,
what need is there to complain to the kazi? Here is your money; it
was only a little joke on my part.” But in the evening, when he went
to receive the kazi’s pretended deposit, he experienced the truth of
the saw, that “covetousness sews up the eyes of cunning.”
A variant of this is found in the continental “Gesta Romanorum” (ch.
cxviii. of Swan’s translation), in which a knight deposits ten talents
with a respectable old man, who when called upon to refund the
money denies all knowledge of it. By the advice of an old woman,
the knight has ten chests made, and employs a person to take them
to the old man and represent them as containing treasure; and while
one of them is being carried into his house the knight enters and in
the stranger’s presence demands his money, which is at once
delivered to him.
In Mr. Edward Rehatsek’s translated selections from the Persian
story-book “Shamsa ú Kuhkuha” (see ante, p. 329), printed at
Bombay in 1871, under the title of “Amusing Stories,” there is a tale
(No. xviii.) which also bears some resemblance to that of the
Melancholist and the Sharper; and as Mr. Rehatsek’s little work is
exceedingly scarce, I give it in extenso as follows:
71. There was in Damascus a man of the name of Zayn el-Arab, with the
honey of whose life the poison of hardships was always mixed. Day
and night he hastened like the breeze from north to south in the
world of exertion, and he was burning brightly like straw, from his
endeavours in the oven of acquisition in order to gain a loaf of bread
and feed his family. In course of time, however, he succeeded in
accumulating a considerable sum of money, but as he had tasted the
bitter poison of destitution, and had for a very long time carried the
heavy load of poverty upon his back, and fearing to lose his property
by the chameleon-like changes of fortune, he took up his money on
a certain night, carried it out of the city, and buried it under a tree.
After some time had passed he began sorely to miss the presence of
his treasure, and betook himself to the tree to refresh his eyes with
the sight of it. But when he dug up the ground at the foot of the
tree he discovered that his soul-exhilarating deposit was refreshing
the palate of some one else. The morning of his prosperity was
suddenly changed into the evening of bitterness and
disappointment. He was perplexed to what friend to confide his
secret, and to what remedy to fly for the recovery of his treasure.
The lancet of grief had pierced the liver of his peace, and the
huntsman of distress had tied up the wings and feet of the bird of
his serenity. One day he went on some business to a learned and
wise man of the city with whom he was on a footing of intimacy.
This man said to him, “It is some time since I perceived the glade of
your circumstances to have been destroyed by the burning coals of
restlessness, and a sad change to have taken place in your health. I
do not know the reason, nor what thorn of misfortune has pierced
the foot of your heart, nor what hardship has dawned from the east
of your mind.” Zayn el-Arab wept tears of sadness and said, “O thou
standard coin from the mint of love! the treachery of misfortune has
brought a strange accident upon me, and the bow of destiny has let
fly an unpropitious arrow upon my feeble target. I have a heavy
heart and great sorrow, and were I to reveal it to you perhaps it
would be of no use and would plunge you also into grief.” The
learned man said, “Since the hearts of intimate friends are like
looking-glasses and are receiving the figures of mutual secrets, it is
72. at all times necessary that they should communicate to each other
any difficulties which they have fallen into, that they may remove
them by taking in common those steps which prudence and
foresight should recommend.” Zayn el-Arab replied, “Dear friend, I
had some gold, and fearing lest it should be stolen, I carried it to
such and such a place and buried it under a tree, and when I again
visited the place, I perceived the garment of my beloved Joseph to
be sprinkled with the blood of the wolf of deception.” The learned
man said, “This is a grave accident, and it will be difficult to get on
the track of your gold. Perhaps some one saw you bury it: he who
has taken it will have to give an account of it in the next world, for
God is omniscient. Give me ten days’ delay, that I may study the
book of expedients and stratagems, when mayhap somewhat will
occur to me.”
That knowing man sat down for ten days in the school of meditation,
and how much so ever he turned over the leaves of the volume of
his mind from the preface to the epilogue, he could hit upon no
plan. On the tenth day they again met in the street, and he said to
Zayn el-Arab, “Although the diver of my mind has plunged deeply
and searched diligently in this deep sea, he has been unable to seize
the precious pearl of a wise plan of operation: may God recompense
you from the stores of His hidden treasury!” They were conversing in
this way when a lunatic met them and said, “Well, my boys, what
secret-mongering have you got between you?” The learned man said
to Zayn el-Arab, “Come, let us relate our case to this crazy fellow, to
see the flower of the plant that may bloom from his mind.” Zayn el-
Arab replied, “Dear friend, you, with all your knowledge, cannot
devise anything during ten days: what information are we likely to
gain from a poor lunatic who does not know whether it is now day
or night?” The learned man said, “There is no telling what he may
say to us. But you know that the most foolish as well as the most
wise have ideas, and a sentence uttered at random has sometimes
furnished a clue by which the desired object may be attained.”
Meanwhile a little boy also came up, and perceiving the lunatic
stopped to see his tricks. The two friends explained their case to the
73. lunatic, who then seemed immersed in thought for some time, after
which he said, “He who took the root of that tree for a medicine also
took the gold,” and having thus spoken, he turned his back upon
them and went his way. They consulted with each other what
indication this remark might furnish, when the little boy, who had
overheard the conversation, asked what kind of a tree it was. Zayn
el-Arab replied that it was a jujube tree. The boy said, “This is an
easy matter: you ought to inquire of all the doctors of this town for
whom a medicine has been prescribed of the roots of this tree.”
They greatly admired the boy’s acuteness and also of the lunatic’s
lucky thought.[512]
The learned man was well acquainted with all the
physicians of the city and made his enquiries, till he met with one
who informed him that about twenty days ago he had prescribed for
a merchant of the name of Khoja Semender, who suffered from
asthma, and that one of the remedies was the root of that jujube
tree. The learned man soon discovered the merchant’s house, found
him enjoying excellent health, and said to him, “Ah, Khoja, all the
goods of this world ought to be surrendered to procure health. By
the blessing of God, you have recovered your health, and you ought
to give up what you found at the root of that tree, because the
owner of it is a worthy man and possesses nothing else.” The honest
merchant answered, “It is true, I have found it, and it is with me. If
you will describe it I will deliver it into your hands.” The exact sum
being stated, the merchant at once delivered up the gold.
In the “Kathá Sarit Ságara,” Book vi. ch. 33, we have probably the
original of this last story: A wealthy merchant provided a Bráhman
with a lodging near his own house, and every day gave him a large
quantity of unhusked rice and other presents, and in course of time
he received like gifts from other great merchants. In this way the
miserly fellow gradually accumulated a thousand dínárs, and going
into the forest he dug a hole and buried it in the ground, and he
went daily to carefully examine the spot. One day, however, he
discovered that his hoard had been stolen, and he went to his friend
the merchant near whose house he lived, and, weeping bitterly, told
74. him of his loss, and that he had resolved to go to a holy bathing-
place and there starve himself to death. The merchant tried to
console him and dissuade him from his resolution, saying, “Bráhman,
why do you long to die for the loss of your wealth? Wealth, like an
unseasonable cloud, suddenly comes and goes.” But the Bráhman
would not abandon his fixed determination to commit suicide, for
wealth is dearer to the miser than life itself. When he was about to
depart for the holy place, the king, having heard of it, came and
asked him, “Bráhman, do you know of any mark by which you can
distinguish the place where you buried your dínárs?” He replied,
“There is a small tree in the wood, at the foot of which I buried that
money.” Then said the king, “I will find the money and give it back
to you, or I will give it you from my own treasury;—do not commit
suicide, Bráhman.”
When the king returned to his palace, he pretended to have a
headache, and summoned all the physicians in the city by
proclamation with beat of drum. And he took aside every one of
them singly and questioned them privately, saying, “What patients
have you, and what medicines have you prescribed for each?” And
they thereupon, one by one, answered the king’s questions. At
length a physician said, “The merchant Mátridatta has been out of
sorts, O king, and this is the second day I have prescribed for him
nágabalá [the plant Uraria Lagopodioides].” Then the king sent for
the merchant, and said to him, “Tell me, who fetched you the
nágabalá?” The merchant replied, “My servant, your highness.” On
hearing this, the king at once summoned the servant and said to
him, “Give up that treasure belonging to a Bráhman, consisting of a
store of dínárs, which you found when you were digging at the foot
of the tree for nágabalá.” When the king said this to him the servant
was frightened, and confessed immediately; and bringing the money
left it there. Then the king summoned the Bráhman and gave him,
who had been fasting meanwhile, the dínárs, lost and found again,
like a second soul external to his body. Thus did the king by his
wisdom recover to the Bráhman his wealth which had been taken
75. away from the root of the tree, knowing that that simple grew in
such spots.
76. TALE OF THE DEVOUT WOMAN ACCUSED OF
LEWDNESS.—Vol. I. p. 270.
This is one of three Arabian variants of Chaucer’s Man of Law’s Tale
(the Story of Constance), of which there are numerous versions—see
my paper entitled “The Innocent Persecuted Wife,” pp. 365–414 of
“Originals and Analogues of some of Chaucer’s Canterbury Tales.”
78. THE WEAVER WHO BECAME A LEACH BY
ORDER OF HIS WIFE.—Vol. I. p. 282.
Somewhat resembling this, but much more elaborate, is the amusing
story of Ahmed the Cobbler, in Sir John Malcolm’s “Sketches of
Persia,” ch. xx., the original of which is probably found in the tale of
Harisarman, book vi. ch. 30, of the “Kathá Sarit Ságara,” and it has
many European variants, such as the German story of Doctor
Allwissend, in Grimm’s collection, and that of the Charcoal Burner in
Sir George Dasent’s “Tales from the Fjeld.”—According to the Persian
story, Ahmed the Cobbler had a young and pretty wife, of whom he
was very fond. She was ever forming grand schemes of riches and
splendour, and was firmly persuaded that she was destined to great
fortune. It happened one evening, while in this frame of mind, that
she went to the public baths, where she saw a lady retiring dressed
in a magnificent robe, covered with jewels, and surrounded by
slaves. This was the very condition she had always longed for, and
she eagerly inquired the name of the happy person who had so
many attendants and such fine jewels. She learned it was the wife of
the chief astrologer to the king. With this information she returned
home. Ahmed met her at the door, but was received with a frown,
nor could all his caresses obtain a smile or a word; for several hours
she continued silent, and in apparent misery; at length she said,
“Cease your caresses, unless you are ready to give me a proof that
you do really and sincerely love me.” “What proof of love,” exclaimed
poor Ahmed, “can you desire that I will not give?” “Give over
cobbling; it is a vile, low trade, and never yields more than ten or
twelve dínárs a day. Turn astrologer; your fortune will be made, and
I shall have all I wish and be happy.” “Astrologer!” cried Ahmed
—“astrologer! Have you forgotten who I am—a cobbler, without any
learning—that you want me to engage in a profession which requires
so much skill and knowledge?” “I neither think nor care about your
qualifications,” said the enraged wife; “all I know is that if you do not
79. turn astrologer immediately, I will be divorced from you to-morrow.”
The cobbler remonstrated, but in vain. The figure of the astrologer’s
wife, with her jewels and her slaves, took complete possession of
her imagination. All night it haunted her: she dreamt of nothing else,
and on awakening declared she would leave the house if her
husband did not comply with her wishes. What could poor Ahmed
do? He was no astrologer; but he was dotingly fond of his wife, and
he could not bear the idea of losing her. He promised to obey; and
having sold his little stock, bought an astrolabe, an astronomical
almanac, and a table of the twelve signs of the zodiac. Furnished
with these, he went to the market-place, crying, “I am an astrologer!
I know the sun, and the moon, and the stars, and the twelve signs
of the zodiac; I can calculate nativities; I can foretell everything that
is to happen.” No man was better known than Ahmed the Cobbler. A
crowd soon gathered round him. “What, friend Ahmed,” said one,
“have you worked till your head is turned?” “Are you tired of looking
down at your last,” cried another, “that you are now looking up at
the stars?” These and a thousand other jokes assailed the ears of
the poor cobbler, who notwithstanding continued to exclaim that he
was an astrologer, having resolved on doing what he could to please
his beautiful wife.
It so happened that the king’s jeweller was passing by. He was in
great distress, having lost the richest ruby belonging to the king.
Every search had been made to recover this inestimable jewel, but
to no purpose; and as the jeweller knew he could no longer conceal
its loss from the king, he looked forward to death as inevitable. In
this hopeless state, while wandering about the town, he reached the
crowd around Ahmed, and asked what was the matter. “Don’t you
know Ahmed the Cobbler?” said one of the bystanders, laughing.
“He has been inspired and is become an astrologer.” A drowning man
will catch at a broken reed: the jeweller no sooner heard the sound
of the word astrologer than he went up to Ahmed, told him what
had happened, and said, “If you understand your art, you must be
able to discover the king’s ruby. Do so, and I will give you two
hundred pieces of gold. But if you do not succeed within six hours, I
80. will use my influence at court to have you put to death as an
impostor.” Poor Ahmed was thunderstruck. He stood long without
being able to speak, reflecting on his misfortunes, and grieving,
above all, that his wife, whom he so loved, had, by her envy and
selfishness, brought him to such a fearful alternative. Full of these
sad thoughts, he exclaimed aloud, “O woman! woman! thou art
more baneful to the happiness of man than the poisonous dragon of
the desert!” Now the lost ruby had been secreted by the jeweller’s
wife, who, disquieted by those alarms which ever attend guilt, sent
one of her female slaves to watch her husband. This slave, on
seeing her master speak to the astrologer, drew near; and when she
heard Ahmed, after some moments of abstraction, compare a
woman to a poisonous dragon, she was satisfied that he must know
everything. She ran to her mistress, and, breathless with fear, cried,
“You are discovered by a vile astrologer! Before six hours are past
the whole story will be known, and you will become infamous, if you
are even so fortunate as to escape with life, unless you can find
some way of prevailing on him to be merciful.” She then related
what she had seen and heard; and Ahmed’s exclamation carried as
complete conviction to the mind of the terrified lady as it had done
to that of her slave. The jeweller’s wife, hastily throwing on her veil,
went in search of the dreaded astrologer. When she found him, she
cried, “Spare my honour and my life, and I will confess everything.”
“What can you have to confess to me?” said Ahmed, in amazement.
“O nothing—nothing with which you are not already acquainted. You
know too well that I stole the king’s ruby. I did so to punish my
husband, who uses me most cruelly; and I thought by this means to
obtain riches for myself and have him put to death. But you, most
wonderful man, from whom nothing is hidden, have discovered and
defeated my wicked plan. I beg only for mercy, and will do whatever
you command me.” An angel from heaven could not have brought
more consolation to Ahmed than did the jeweller’s wife. He assumed
all the dignified solemnity that became his new character, and said,
“Woman! I know all thou hast done, and it is fortunate for thee that
thou hast come to confess thy sin and beg for mercy before it was
too late. Return to thy house; put the ruby under the pillow of the