100% found this document useful (1 vote)
10 views

Beginning ReactJS Foundations Building User Interfaces with ReactJS An Approachable Guide 1st Edition Chris Minnick pdf download

The document is a comprehensive guide titled 'Beginning ReactJS Foundations: Building User Interfaces with ReactJS' by Chris Minnick, aimed at helping readers understand and build user interfaces using ReactJS. It covers foundational concepts, JSX, components, data flow, events, forms, styling, hooks, routing, and deployment, among other topics. The book is structured with clear chapters, practical examples, and resources for further learning.

Uploaded by

alvydanalier
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
10 views

Beginning ReactJS Foundations Building User Interfaces with ReactJS An Approachable Guide 1st Edition Chris Minnick pdf download

The document is a comprehensive guide titled 'Beginning ReactJS Foundations: Building User Interfaces with ReactJS' by Chris Minnick, aimed at helping readers understand and build user interfaces using ReactJS. It covers foundational concepts, JSX, components, data flow, events, forms, styling, hooks, routing, and deployment, among other topics. The book is structured with clear chapters, practical examples, and resources for further learning.

Uploaded by

alvydanalier
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

Beginning ReactJS Foundations Building User

Interfaces with ReactJS An Approachable Guide


1st Edition Chris Minnick download

https://ebookmeta.com/product/beginning-reactjs-foundations-
building-user-interfaces-with-reactjs-an-approachable-guide-1st-
edition-chris-minnick-2/

Download more ebook from https://ebookmeta.com


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!

Beginning ReactJS Foundations Building User Interfaces


with ReactJS: An Approachable Guide 1st Edition Chris
Minnick

https://ebookmeta.com/product/beginning-reactjs-foundations-
building-user-interfaces-with-reactjs-an-approachable-guide-1st-
edition-chris-minnick/

Learn JavaFX 17: Building User Experience and


Interfaces with Java Sharan

https://ebookmeta.com/product/learn-javafx-17-building-user-
experience-and-interfaces-with-java-sharan/

Strategic Communication and AI: Public Relations with


Intelligent User Interfaces 1st Edition Simon Moore

https://ebookmeta.com/product/strategic-communication-and-ai-
public-relations-with-intelligent-user-interfaces-1st-edition-
simon-moore/

Beneath The Surface 1st Edition M.A. Church.

https://ebookmeta.com/product/beneath-the-surface-1st-edition-m-
a-church/
Lectures on Stochastic Programming Modeling and Theory
2nd Edition Alexander Shapiro

https://ebookmeta.com/product/lectures-on-stochastic-programming-
modeling-and-theory-2nd-edition-alexander-shapiro/

Hangman Island 1st Edition Kate Rhodes

https://ebookmeta.com/product/hangman-island-1st-edition-kate-
rhodes/

Fighting Tooth Nail Kings Gym Book 2 1st Edition Shaw


Hart

https://ebookmeta.com/product/fighting-tooth-nail-kings-gym-
book-2-1st-edition-shaw-hart/

OSINT Techniques Resources for Uncovering Online


Information 10th Edition 2023 Michael Bazzell

https://ebookmeta.com/product/osint-techniques-resources-for-
uncovering-online-information-10th-edition-2023-michael-bazzell/

PDZ Mediated Interactions Jean Paul Borg

https://ebookmeta.com/product/pdz-mediated-interactions-jean-
paul-borg/
Compressor Handbook Principles and Practice 2nd Edition
Tony Giampaolo

https://ebookmeta.com/product/compressor-handbook-principles-and-
practice-2nd-edition-tony-giampaolo/
Table of Contents
COVER
TITLE PAGE
INTRODUCTION
WHY THIS BOOK?
WHAT'S COVERED IN THIS BOOK?
WHAT'S NOT COVERED?
PREREQUISITES
INSTALLING REQUIRED DEPENDENCIES
READER SUPPORT FOR THIS BOOK
1 Hello, World!
REACT WITHOUT A BUILD TOOLCHAIN
INTERACTIVE “HELLO, WORLD” WITH CREATE REACT
APP AND JSX
SUMMARY
2 The Foundation of React
WHAT'S IN A NAME?
UI LAYER
VIRTUAL DOM
THE PHILOSOPHY OF REACT
SUMMARY
3 JSX
JSX IS NOT HTML
WHAT IS JSX?
SYNTAX BASICS OF JSX
SUMMARY
4 All About Components
WHAT IS A COMPONENT?
COMPONENTS VS. ELEMENTS
BUILT-IN COMPONENTS
USER-DEFINED COMPONENTS
TYPES OF COMPONENTS
REACT COMPONENT CHILDREN
THE COMPONENT LIFECYCLE
RENDERING COMPONENTS
COMPONENT TERMINOLOGY
SUMMARY
5 React DevTools
INSTALLATION AND GETTING STARTED
INSPECTING COMPONENTS
EDITING COMPONENT DATA IN DEVTOOLS
WORKING WITH ADDITIONAL DEVTOOLS
FUNCTIONALITY
PROFILING
SUMMARY
6 React Data Flow
ONE-WAY DATA FLOW
PROPS
REACT STATE
CONVERTING TO CLASS COMPONENTS
SUMMARY
7 Events
HOW EVENTS WORK IN REACT
WHAT IS SYNTHETICEVENT?
USING EVENT LISTENER ATTRIBUTES
THE EVENT OBJECT
SUPPORTED EVENTS
EVENT HANDLER FUNCTIONS
SUMMARY
8 Forms
FORMS HAVE STATE
CONTROLLED INPUTS VS. UNCONTROLLED INPUTS
LIFTING UP INPUT STATE
USING UNCONTROLLED INPUTS
USING DIFFERENT FORM ELEMENTS
PREVENTING DEFAULT ACTIONS
SUMMARY
9 Refs
WHAT REFS ARE
HOW TO CREATE A REF IN A CLASS COMPONENT
HOW TO CREATE A REF IN A FUNCTION COMPONENT
USING REFS
CREATING A CALLBACK REF
WHEN TO USE REFS
WHEN NOT TO USE REFS
EXAMPLES
SUMMARY
10 Styling React
THE IMPORTANCE OF STYLES
IMPORTING CSS INTO THE HTML FILE
USING PLAIN OLD CSS IN COMPONENTS
WRITING INLINE STYLES
CSS MODULES
CSS-IN-JS AND STYLED COMPONENTS
SUMMARY
11 Introducing Hooks
WHAT ARE HOOKS?
WHY WERE HOOKS INTRODUCED?
RULES OF HOOKS
THE BUILT-IN HOOKS
WRITING CUSTOM HOOKS
LABELING CUSTOM HOOKS WITH USEDEBUGVALUE
FINDING AND USING CUSTOM HOOKS
SUMMARY
12 Routing
WHAT IS ROUTING?
HOW ROUTING WORKS IN REACT
USING REACT ROUTER
REACT ROUTER HOOKS
SUMMARY
13 Error Boundaries
THE BEST LAID PLANS
WHAT IS AN ERROR BOUNDARY?
IMPLEMENTING AN ERROR BOUNDARY
WHAT CAN'T AN ERROR BOUNDARY CATCH?
SUMMARY
14 Deploying React
WHAT IS DEPLOYMENT?
BUILDING AN APP
HOW IS A DEPLOYED APP DIFFERENT?
DEVELOPMENT MODE VS. PRODUCTION
PUTTING IT ON THE WEB
SUMMARY
15 Initialize a React Project from Scratch
BUILDING YOUR OWN TOOLCHAIN
HOW WEBPACK WORKS
AUTOMATING YOUR BUILD PROCESS
STRUCTURING YOUR SOURCE DIRECTORY
SUMMARY
16 Fetching and Caching Data
ASYNCHRONOUS CODE: IT'S ALL ABOUT TIMING
JAVASCRIPT NEVER SLEEPS
WHERE TO RUN ASYNC CODE IN REACT
WAYS TO FETCH
GETTING DATA WITH FETCH
GETTING DATA WITH AXIOS
USING WEB STORAGE
SUMMARY
17 Context API
WHAT IS PROP DRILLING?
HOW CONTEXT API SOLVES THE PROBLEM
COMMON USE CASES FOR CONTEXT
WHEN NOT TO USE CONTEXT
COMPOSITION AS AN ALTERNATIVE TO CONTEXT
EXAMPLE APP: USER PREFERENCES
SUMMARY
18 React Portals
WHAT IS A PORTAL?
COMMON USE CASES
SUMMARY
19 Accessibility in React
WHY IS ACCESSIBILITY IMPORTANT?
ACCESSIBILITY BASICS
IMPLEMENTING ACCESSIBILITY IN REACT
COMPONENTS
SUMMARY
20 Going Further
TESTING
SERVER-SIDE RENDERING
PEOPLE TO FOLLOW
USEFUL LINKS AND RESOURCES
SUMMARY
INDEX
COPYRIGHT
DEDICATION
ABOUT THE AUTHOR
ABOUT THE TECHNICAL EDITOR
ACKNOWLEDGMENTS
END USER LICENSE AGREEMENT

List of Tables
Chapter 4
TABLE 4-1: HTML Elements Supported by React
TABLE 4-2: Functions vs. Classes
Chapter 6
TABLE 6-1: Comparing props and state
Chapter 7
TABLE 7-1: Events Supported by React
Chapter 12
TABLE 12-1: Properties and Methods of history

List of Illustrations
Introduction
FIGURE I-1: VS Code
FIGURE I-2: Download VS Code
FIGURE I-3: The VS Code welcome screen
FIGURE I-4: The VS Code Command Palette
FIGURE I-5: Creating a new file using the Command
Palette
FIGURE I-6: Using Emmet to save typing
FIGURE I-7: Client-side React and server-side Node
FIGURE I-8: Development, client-side, and server-side
FIGURE I-9: Minification
FIGURE I-10: Transpiling example
FIGURE I-11: Module bundling
FIGURE I-12: The VS Code Terminal
FIGURE I-13: Checking that npm is installed
FIGURE I-14: Chrome DevTools
FIGURE I-15: React Developer Tools Components view
FIGURE I-16: The default Create React App boilerplate
Chapter 1
FIGURE 1-1: The React CDN Links
FIGURE 1-2: Hello, World running in a browser
FIGURE 1-3: The finished interactive Hello, World
component!
Chapter 2
FIGURE 2-1: The MVC pattern
FIGURE 2-2: React and ReactDOM
FIGURE 2-3: How the Virtual DOM works
FIGURE 2-4: How the web works
Chapter 3
FIGURE 3-1: Trying out Babel on the web
Chapter 4
FIGURE 4-1: A tree of react components
FIGURE 4-2: Using state immediately after calling
setState() may produce une...
FIGURE 4-3: The result of rendering FigureList
FIGURE 4-4: Rendering the ThingsILike component
FIGURE 4-5: The component lifecycle
FIGURE 4-6: Incrementing a counter
FIGURE 4-7: The result of attempting to call setState on an
unmounted compon...
FIGURE 4-8: Hello, React Native
Chapter 5
FIGURE 5-1: The React Bookstore sample app
FIGURE 5-2: The Chrome Developer Tools with React
DevTools installed
FIGURE 5-3: The React DevTools Components tab
FIGURE 5-4: The component tree with ProductList
collapsed
FIGURE 5-5: Creating new CartItem children
FIGURE 5-6: Searching for components containing “c”
FIGURE 5-7: Searching for components starting with “c”
FIGURE 5-8: React DevTools' View Settings
FIGURE 5-9: The component tree view with the default
filter disabled
FIGURE 5-10: The React DevTools Select tool
FIGURE 5-11: Viewing component details
FIGURE 5-12: Attempting to add an out-of-range ID to the
cart
FIGURE 5-13: Logging component data to the console
FIGURE 5-14: The Flamegraph chart
FIGURE 5-15: Viewing the Ranked chart
FIGURE 5-16: Ranked chart after optimizing
Chapter 6
FIGURE 6-1: Unidirectional data flow
FIGURE 6-2: Bidirectional data flow
FIGURE 6-3: Data flowing in one direction
FIGURE 6-4: Changing local variables doesn't update the
view
FIGURE 6-5: Local variable and props confusion
FIGURE 6-6: Passing the wrong prop type
FIGURE 6-7: PropTypes displaying a warning
FIGURE 6-8: The not-renderable error message
FIGURE 6-9: PropTypes tell which attribute caused the
error
FIGURE 6-10: Failing PropTypes.element validation
FIGURE 6-11: A custom PropType validator failing
FIGURE 6-12: The result of clicking the CounterClass
button
FIGURE 6-13: The fixed counter class
FIGURE 6-14: A reminders app
FIGURE 6-15: The first round static version
FIGURE 6-16: A static version of the Reminders app
FIGURE 6-17: Cannot read property
FIGURE 6-18: Cannot read property ‘map' of undefined
FIGURE 6-19: Displaying the default prop
FIGURE 6-20: The initial render of the Reminders app
FIGURE 6-21: Adding Reminders to the list
FIGURE 6-22: Checking and unchecking isComplete
checkboxes
Chapter 7
FIGURE 7-1: Viewing the properties of a SyntheticEvent
FIGURE 7-2: The NativeEvent properties
Chapter 8
FIGURE 8-1: Controlled and uncontrolled inputs
FIGURE 8-2: Rendering an uncontrolled input
FIGURE 8-3: Form input often affects other components
Chapter 9
FIGURE 9-1: The TextReader component
FIGURE 9-2: Selecting text and displaying a temporary
message
Chapter 10
FIGURE 10-1: Cascading styles from parent to child
Chapter 11
FIGURE 11-1: Wrapper hell
FIGURE 11-2: Passing a setter function as a prop
FIGURE 11-3: Starting a new timer with each render
FIGURE 11-4: Running an effect only after mounting
FIGURE 11-5: Performing an asynchronous request using
useEffect
FIGURE 11-6: Unnecessary renders warning due to a
function dependency
FIGURE 11-7: Testing referential equality
FIGURE 11-8: Inspecting a custom hook
FIGURE 11-9: Viewing a Custom Hook's debug value
Chapter 12
FIGURE 12-1: How the web works
FIGURE 12-2: JavaScript routing
FIGURE 12-3: Changing routes and viewing the
window.location.href property
FIGURE 12-4: React Router can't be used for external
linking
FIGURE 12-5: Navigation links indicate the current position
FIGURE 12-6: A navigation menu with sub-items
FIGURE 12-7: Partial matches activate the active style
FIGURE 12-8: Using the exact attribute on NavLink
components
FIGURE 12-9: Multiple routes can match the URL
FIGURE 12-10: Add the exact attribute to Routes to restrict
matching
FIGURE 12-11: Modifying the current location
FIGURE 12-12: Dynamic link and path attributes with the
match object propert...
Chapter 13
FIGURE 13-1: A crashed React app
FIGURE 13-2: A diagram of a typical UI
FIGURE 13-3: An uncaught error
FIGURE 13-4: Handling an error with an error boundary
FIGURE 13-5: Rendering a fallback UI
FIGURE 13-6: Viewing the error and info parameters in the
console
FIGURE 13-7: Add a log source
FIGURE 13-8: The Customer Token link in Loggly
FIGURE 13-9: Viewing caught errors in Loggly
FIGURE 13-10: Providing a reset option in the error
boundary
Chapter 14
FIGURE 14-1: The build directory
FIGURE 14-2: The minified and compiled index.html
FIGURE 14-3: Running a built app from the filesystem
FIGURE 14-4: Development vs. production in the
Developer Tools
FIGURE 14-5: Click the New site from Git button
FIGURE 14-6: Choose your Git provider
FIGURE 14-7: Choose a repository
FIGURE 14-8: A deployed React app
FIGURE 14-9: Domain management in Netlify
Chapter 15
FIGURE 15-1: Attempting to load index.js without
compiling
FIGURE 15-2: JSX requires a loader
FIGURE 15-3: The working React app
FIGURE 15-4: Starting the configuration wizard
FIGURE 15-5: Automatically fixable errors or warnings
FIGURE 15-6: No tests found
FIGURE 15-7: Test passed
FIGURE 15-8: Grouping by file type
FIGURE 15-9: Grouping by features
Chapter 16
FIGURE 16-1: Executing asynchronous JavaScript
FIGURE 16-2: How asynchronous tasks are handled
FIGURE 16-3: Remembering a user with Web Storage
FIGURE 16-4: Viewing Local Storage in Chrome Developer
Tools
Chapter 17
FIGURE 17-1: Using a component outside of its Context
FIGURE 17-2: A user preferences component with Context
Chapter 18
FIGURE 18-1: Portals enable modal dialogs
FIGURE 18-2: Rendering the SalesChart component
FIGURE 18-3: Inspecting an app with a Portal in Chrome
Developer Tools
FIGURE 18-4: Inspecting an app with a Portal in React
Developer Tools
FIGURE 18-5: Rendering a modal without using React
Portals can have unexpect...
FIGURE 18-6: The opened modal
FIGURE 18-7: A checkout form with help links
Chapter 20
FIGURE 20-1: The Flux pattern
FIGURE 20-2: Data flow in a Redux application
BEGINNING
ReactJS Foundations
Building User Interfaces with
ReactJS

AN APPROACHABLE GUIDE

Chris Minnick
Discovering Diverse Content Through
Random Scribd Documents
The craft most frequently practised by my ancestors seems {5} to
have been that of a goldsmith, although several are believed to have
practised less dignified trades.
In the time of Henry the Eighth one of my ancestors, together
with a hundred men, were taken prisoners at the siege of Calais.
When William the Third landed in Torbay, another ancestor of
mine, a yeoman possessing some small estate, undertook to
distribute his proclamations. For this bit of high treason he was
rewarded with a silver medal, which I well remember seeing, when I
was a boy. It had descended to a very venerable and truthful old
lady, an unmarried aunt, the historian of our family, on whose
authority the identity of the medal I saw with that given by King
William must rest.
Another ancestor married one of two daughters, the only children
of a wealthy physician, Dr. Burthogge, an intimate friend and cor­res­‐
pon­dent of John Locke.
〈A WILD ANCESTOR.〉

Somewhere about 1700 a member of my family, one Richard


Babbage, who appears to have been a very wild fellow, having tried
his hand at various trades, and given them all up, offended a
wealthy relative.
To punish this idleness, his relative entailed all his large estates
upon eleven different people, after whom he gave it to this Richard
Babbage, who, had there been no entail, would have taken them as
heir-at-law.
Ten of these lives had dropped, and the eleventh was in a
consumption, when Richard Babbage took it into his head to go off
to America with Bamfylde Moore Carew, the King of the Beggars.
The last only of the eleven lives existed when he embarked, and
that life expired within twelve months after Richard Babbage sailed.
The estates remained in possession of the rep­re­sen­ta­tives of the
eleventh in the entail. {6}
If it could have been proved that Richard Babbage had survived
twelve months after his voyage to America, these estates would
have remained in my own branch of the family.
I possess a letter from Richard Babbage, dated on board the ship
in which he sailed for America.
〈ACT OF PARLIAMENT.〉

In the year 1773 it became necessary to sell a portion of this


property, for the purpose of building a church at Ashbrenton. A
private Act of Parliament was passed for that purpose, in which the
rights of the true heir were reserved.
CHAPTER II.
CHILDHOOD.

“The Prince of Darkness is a gentleman.”—Hamlet.

Early Passion for inquiry and inquisition into Toys — Lost on London Bridge —
Supposed value of the young Phi­los­o­pher — Found again — Strange Coincidence in
after-years — Poisoned — Frightened a Schoolfellow by a Ghost — Frightened himself
by trying to raise the Devil — Effect of Want of Occupation for the Mind — Treasure-
trove — Death and Non-appearance of a Schoolfellow.

F ROM my earliest years I had a great desire to inquire into the


causes of all those little things and events which astonish the
childish mind. At a later period I commenced the still more important
inquiry into those laws of thought and those aids which assist the
human mind in passing from received knowledge to that other
knowledge then unknown to our race. I now think it fit to record
some of those views to which, at various periods of my life, my
reasoning has led me. Truth only has been the object of my search,
and I am not conscious of ever having turned aside in my inquiries
from any fear of the conclusions to which they might lead.
As it may be interesting to some of those who will hereafter read
these lines, I shall briefly mention a few events of my earliest, and
even of my childish years. My parents being born at a certain period
of history, and in a certain latitude and longitude, of course followed
the religion {8} of their country. They brought me up in the
Protestant form of the Christian faith. My excellent mother taught
me the usual forms of my daily and nightly prayer; and neither in my
father nor my mother was there any mixture of bigotry and
intolerance on the one hand, nor on the other of that unbecoming
and familiar mode of addressing the Almighty which afterwards so
much disgusted me in my youthful years.
My invariable question on receiving any new toy, was “Mamma,
what is inside of it?” Until this information was obtained those
around me had no repose, and the toy itself, I have been told, was
generally broken open if the answer did not satisfy my own little
ideas of the “fitness of things.”
Earliest Recollections.
Two events which impressed themselves forcibly on my memory
happened, I think, previously to my eighth year.
〈THE YOUNG PHI­LOS­O­PHER LOST.〉

When about five years old, I was walking with my nurse, who
had in her arms an infant brother of mine, across London Bridge,
holding, as I thought, by her apron. I was looking at the ships in the
river. On turning round to speak to her, I found that my nurse was
not there, and that I was alone upon London Bridge. My mother had
always impressed upon me the necessity of great caution in passing
any street-crossing: I went on, therefore, quietly until I reached
Tooley Street, where I remained watching the passing vehicles, in
order to find a safe opportunity of crossing that very busy street.
〈THE CRI­ER OF­FERS A RE­WARD.〉

In the mean time the nurse, having lost one of her charges, had
gone to the crier, who proceeded immediately to call, by the ringing
of his bell, the attention of the public to the fact that a young phi­los­‐
o­pher was lost, and to the still more important fact that five shillings
would be the reward of his fortunate discoverer. I well remember
sitting on the steps of {9} the door of the linendraper’s shop on the
opposite corner of Tooley Street, when the gold-laced crier was
making proclamation of my loss; but I was too much occupied with
eating some pears to attend to what he was saying.
The fact was, that one of the men in the linendraper’s shop,
observing a little child by itself, went over to it, and asked what it
wanted. Finding that it had lost its nurse, he brought it across the
street, gave it some pears, and placed it on the steps at the door:
having asked my name, the shopkeeper found it to be that of one of
his own customers. He accordingly sent off a messenger, who
announced to my mother the finding of young Pickle before she was
aware of his loss.
Those who delight in observing coincidences may perhaps
account for the following singular one. Several years ago when the
houses in Tooley Street were being pulled down, I believe to make
room for the new railway terminus, I happened to pass along the
very spot on which I had been lost in my infancy. A slate of the
2
largest size, called a Duchess, was thrown from the roof of one of
the houses, and penetrated into the earth close to my feet.
2 There exists an aristocracy even amongst slates, perhaps from their occupying
the most elevated position in every house. Small ones are called Ladies, a larger
size Countesses, and the biggest of all are Duchesses.

The other event, which I believe happened some time after the
one just related, is as follows. I give it from memory, as I have
always repeated it.
〈YOUNG PHI­LOS­O­PHER POISONED.〉

I was walking with my nurse and my brother in a public garden,


called Mont­pel­ier Gar­dens, in Wal­worth. On returning through the
private road leading to the gardens, I gathered and swallowed some
dark berries very like black currants:—these were poisonous. {10}
On my return home, I recollect being placed between my father’s
knees, and his giving me a glass of castor oil, which I took from his
hand.
My father at that time possessed a collection of pictures. He sat
on a chair on the right hand side of the chimney-piece in the
breakfast room, under a fine picture of our Saviour taken down from
the cross. On the opposite wall was a still-celebrated “Interior of
Antwerp Cathedral.”
In after-life I several times mentioned the subject both to my
father and to my mother; but neither of them had the slightest
recollection of the matter.
Having suffered in health at the age of five years, and again at
that of ten by violent fevers, from which I was with difficulty saved, I
was sent into Devonshire and placed under the care of a clergyman
(who kept a school at Alphington, near Exeter), with in­struc­tions to
attend to my health; but, not to press too much knowledge upon
me: a mission which he faithfully accomplished. Perhaps great
idleness may have led to some of my childish reasonings.
Relations of ghost stories often circulate amongst children, and
also of visitations from the devil in a personal form. Of course I
shared the belief of my comrades, but still had some doubts of the
existence of these personages, although I greatly feared their
appearance. Once, in conjunction with a companion, I frightened
another boy, bigger than myself, with some pretended ghost; how
prepared or how represented by natural objects I do not now
remember: I believe it was by the accidental passing shadows of
some external objects upon the walls of our common bedroom.
〈DELUDES A BOY WITH A GHOST.〉

The effect of this on my playfellow was painful; he was much


frightened for several days; and it naturally occurred to me, after
some time, that as I had deluded him with ghosts, {11} I might
myself have been deluded by older persons, and that, after all, it
might be a doubtful point whether ghost or devil ever really existed.
I gathered all the information I could on the subject from the other
boys, and was soon informed that there was a peculiar process by
which the devil might be raised and become personally visible. I
carefully collected from the traditions of different boys the visible
forms in which the Prince of Darkness had been recorded to have
appeared. Amongst them were—

A rabbit,
An owl,
A black cat, very frequently,
A raven,
A man with a cloven foot, also frequent.
After long thinking over the subject, although checked by a belief
that the inquiry was wicked, my curiosity at length over-balanced my
fears, and I resolved to attempt to raise the devil. Naughty people, I
was told, had made written compacts with the devil, and had signed
them with their names written in their own blood. These had
become very rich and great men during their life, a fact which might
be well known. But, after death, they were described as having
suffered and continuing to suffer physical torments throughout
eternity, another fact which, to my uninstructed mind, it seemed
difficult to prove.
As I only desired an interview with the gentleman in black simply
to convince my senses of his existence, I declined adopting the legal
forms of a bond, and preferred one more resembling that of leaving
a visiting card, when, if not at home, I might expect the sat­is­fac­tion
of a return of the visit by the devil in person. {12}
〈TRIES TO RAISE THE DEVIL.〉

Accordingly, having selected a promising locality, I went one


evening towards dusk up into a deserted garret. Having closed the
door, and I believe opened the window, I proceeded to cut my finger
and draw a circle on the floor with the blood which flowed from the
incision.
I then placed myself in the centre of the circle, and either said or
read the Lord’s Prayer backwards. This I accomplished at first with
some trepidation and in great fear towards the close of the scene. I
then stood still in the centre of that magic and superstitious circle,
looking with intense anxiety in all directions, especially at the
window and at the chimney. Fortunately for myself, and for the
reader also, if he is interested in this narrative, no owl or black cat or
unlucky raven came into the room.
In either case my then weakened frame might have expiated this
foolish experiment by its own extinction, or by the alienation of that
too curious spirit which controlled its feeble powers.
〈EXPERIMENTAL RELIGION.〉

After waiting some time for my expected but dreaded visitor, I, in


some degree, recovered my self-possession, and leaving the circle of
my incantation, I gradually opened the door and gently closing it,
descended the stairs, at first slowly, and by degrees much more
quickly. I then rejoined my companions, but said nothing whatever
of my recent attempt. After supper the boys retired to bed. When
we were in bed and the candle removed, I proceeded as usual to
repeat my prayers silently to myself. After the few first sentences of
the Lord’s Prayer, I found that I had forgotten a sentence, and could
not go on to the conclusion. This alarmed me very much, and having
repeated another prayer or hymn, I remained long awake, and very
unhappy. I thought that this forgetfulness was a punishment inflicted
{13} upon me by the Almighty, and that I was a wicked little boy for

having attempted to satisfy myself about the existence of a devil.


The next night my memory was more faithful, and my prayers went
on as usual. Still, however, I was unhappy, and continued to brood
over the inquiry. My uninstructed faculties led me from doubts of the
existence of a devil to doubts of the book and the religion which
asserted him to be a living being. My sense of justice (whether it be
innate or acquired) led me to believe that it was impossible that an
almighty and all-merciful God could punish me, a poor little boy, with
eternal torments because I had anxiously taken the only means I
knew of to verify the truth or falsehood of the religion I had been
taught. I thought over these things for a long time, and, in my own
childish mind, wished and prayed that God would tell me what was
true. After long meditation, I resolved to make an experiment to
settle the question. I thought, if it was really of such immense
importance to me here and hereafter to believe rightly, that the
Almighty would not consign me to eternal misery because, after
trying all means that I could devise, I was unable to know the truth.
I took an odd mode of making the experiment; I resolved that at a
certain hour of a certain day I would go to a certain room in the
house, and that if I found the door open, I would believe the Bible;
but that if it were closed, I should conclude that it was not true. I
remember well that the ob­ser­va­tion was made, but I have no
recollection as to the state of the door. I presume it was found open
from the circumstance that, for many years after, I was no longer
troubled by doubts, and indeed went through the usual religious
forms with very little thought about their origin.
〈DISCOVERY OF GOLD.〉

At length, as time went on, my bodily health was restored {14} by


my native air: my mind, however, receiving but little in­struc­tion,
began, I imagine, to prey upon itself—such at least I infer to have
been the case from the following circumstance. One day, when
uninterested in the sports of my little companions, I had retired into
the shrubbery and was leaning my head, supported by my left arm,
upon the lower branch of a thorn-tree. Listless and unoccupied, I
imagined I had a head-ache. After a time I perceived, lying on the
ground just under me, a small bright bit of metal. I instantly seized
the precious discovery, and turning it over, examined both sides. I
immediately concluded that I had discovered some valuable
treasure, and running away to my deserted companions, showed
them my golden coin. The little company became greatly excited,
and declared that it must be gold, and that it was a piece of money
of great value. We ran off to get the opinion of the usher; but
whether he partook of the delusion, or we acquired our knowledge
from the higher authority of the master, I know not. I only recollect
the entire dissipation of my head-ache, and then my ultimate great
disappointment when it was pronounced, upon the undoubted
authority of the village doctor, that the square piece of brass I had
found was a half-dram weight which had escaped from the box of a
pair of medical scales. This little incident had an important effect
upon my after-life. I reflected upon the extraordinary fact, that my
head-ache had been entirely cured by the discovery of the piece of
brass. Although I may not have put into words the principle, that
occupation of the mind is such a source of pleasure that it can
relieve even the pain of a head-ache; yet I am sure it practically
gave an additional stimulus to me in many a difficult inquiry. Some
few years after, when suffering under a form of tooth-ache, not
acute though tediously {15} wearing, I often had recourse to a
volume of Don Quixote, and still more frequently to one of Robinson
Crusoe. Although at first it required a painful effort of attention, yet
it almost always happened, after a time, that I had forgotten the
moderate pain in the overpowering interest of the novel.
〈COMPACT TO APPEAR AFTER DEATH.〉

My most intimate companion and friend was a boy named


Dacres, the son of Admiral Richard Dacres. We had often talked over
such questions as those I have mentioned in this chapter, and we
had made an agreement that whichever died first should, if possible,
appear to the other after death, in order to satisfy the survivor about
their solution.
After a year or two my young friend entered the navy, but we
kept up our friendship, and when he was ashore I saw him
frequently. He was in a ship of eighty guns at the passage of the
Dardanelles, under the command of Sir Thomas Duckworth.
Ultimately he was sent home in charge of a prize-ship, in which he
suffered the severest hardships during a long and tempestuous
voyage, and then died of consumption.
I saw him a few days before his death, at the age of about
eighteen. We talked of former times, but neither of us mentioned
the compact. I believe it occurred to his mind: it was certainly
strongly present to my own.
〈DID NOT APPEAR.〉

He died a few days after. On the evening of that day I retired to


my own room, which was partially detached from the house by an
intervening conservatory. I sat up until after midnight, endeavouring
to read, but found it impossible to fix my attention on any subject,
except the overpowering feeling of curiosity, which absorbed my
mind. I then undressed and went into bed; but sleep was entirely
banished. I had previously carefully examined whether any cat, bird,
or living animal might be accidentally concealed in my room, {16} and
I had studied the forms of the furniture lest they should in the
darkness mislead me.
I passed a night of perfect sleeplessness. The distant clock and a
faithful dog, just outside my own door, produced the only sounds
which disturbed the intense silence of that anxious night.
CHAPTER III.
BOYHOOD.

Taken to an Exhibition of Mechanism — Silver Ladies — School near London —


Unjustly punished — Injurious Effect — Ward’s Young Mathematician’s Guide — Got
up in the Night to Study — Frederick Marryat interrupts — Treaty of Peace — Found
out — Strange Effect of Treacle and Cognac on Boys — Taught to write Sermons
under the Rev. Charles Simeon.

D URING my boyhood my mother took me to several exhibitions of


machinery. I well remember one of them in Hanover Square, by a
man who called himself Merlin. I was so greatly interested in it, that
the Exhibitor remarked the circumstance, and after explaining some
of the objects to which the public had access, proposed to my
mother to take me up to his workshop, where I should see still more
wonderful automata. We accordingly ascended to the attic. There
were two uncovered female figures of silver, about twelve inches
high.
One of these walked or rather glided along a space of about four
feet, when she turned round and went back to her original place.
She used an eye-glass oc­ca­sion­al­ly, and bowed frequently, as if
recognizing her acquaintances. The motions of her limbs were
singularly graceful.
The other silver figure was an admirable danseuse, with a bird on
the fore finger of her right hand, which wagged its tail, flapped its
wings, and opened its beak. This lady attitudinized in a most
fascinating manner. Her eyes were full of imagination, and
irresistible. {18}
These silver figures were the chef-d’œuvres of the artist: they
had cost him years of unwearied labour, and were not even then
finished.
After I left Devonshire I was placed at a school in the
neighbourhood of London, in which there were about thirty boys.
〈UNJUST PUNISHMENT.〉

My first experience was unfortunate, and prob­a­bly gave an un­fa­‐


vour­a­ble turn to my whole career during my residence of three
years.
After I had been at school a few weeks, I went with one of my
companions into the play-ground in the dusk of the evening. We
heard a noise, as of people talking in an orchard at some distance,
which belonged to our master. As the orchard had recently been
robbed, we thought that thieves were again at work. We accordingly
climbed over the boundary wall, ran across the field, and saw in the
orchard beyond a couple of fellows evidently running away. We
pursued as fast as our legs could carry us, and just got up to the
supposed thieves at the ditch on the opposite side of the orchard.
A roar of laughter then greeted us from two of our own
companions, who had entered the orchard for the purpose of getting
some manure for their flowers out of a rotten mulberry-tree. These
boys were aware of our mistake, and had humoured it.
We now returned all together towards the play-ground, when we
met our master, who immediately pronounced that we were each
fined one shilling for being out of bounds. We two boys who had
gone out of bounds to protect our master’s property, and who if
thieves had really been there would probably have been half-killed
by them, attempted to remonstrate and explain the case; but all {19}
remonstrance was vain, and we were accordingly fined. I never
forgot that injustice.
The school-room adjoined the house, but was not directly
connected with it. It contained a library of about three hundred
volumes on various subjects, generally very well selected; it also
contained one or two works on subjects which do not usually attract
at that period of life. I derived much advantage from this library; and
I now mention it because I think it of great importance that a library
should exist in every school-room.
〈NIGHT WORK.〉

Amongst the books was a treatise on Algebra, called “Ward’s


Young Mathematician’s Guide.” I was always partial to my
arithmetical lessons, but this book attracted my particular attention.
After I had been at this school for about a twelvemonth, I proposed
to one of my school-fellows, who was of a studious habit, that we
should get up every morning at three o’clock, light a fire in the
school-room, and work until five or half-past five. We accomplished
this pretty regularly for several months. Our plan had, however,
become partially known to a few of our companions. One of these, a
tall boy, bigger than ourselves, having heard of it, asked me to allow
him to get up with us, urging that his sole object was to study, and
that it would be of great importance to him in after-life. I had the
cruelty to refuse this very reasonable request. The subject has often
recurred to my memory, but never without regret.
〈RIVAL COMPETITORS.〉
3
Another of my young companions, Frederick Marryat, made the
same request, but not with the same motive. I told him we got up in
order to work; that he would only play, and that we should then be
found out. After some time, having exhausted all his arguments,
Marryat told me he was {20} determined to get up, and would do it
whether I liked it or not.
3 Afterwards Captain Marryat.

Marryat slept in the same room as myself: it contained five beds.


Our room opened upon a landing, and its door was exactly opposite
that of the master. A flight of stairs led up to a passage just over the
room in which the master and mistress slept. Passing along this
passage, another flight of stairs led down, on the other side of the
master’s bed-room, to another landing, from which another flight of
stairs led down to the external door of the house, leading by a long
passage to the school-room.
Through this devious course I had cautiously threaded my way,
calling up my companion in his room at the top of the last flight of
stairs, almost every night for several months.
One night on trying to open the door of my own bed-room, I
found Marryat’s bed projecting a little before the door, so that I
could not open it. I perceived that this was done purposely, in order
that I might awaken him. I therefore cautiously, and by degrees,
pushed his bed back without awaking him, and went as usual to my
work. This occurred two or three nights successively.
One night, however, I found a piece of pack-thread tied to the
door lock, which I traced to Marryat’s bed, and concluded it was tied
to his arm or hand. I merely untied the cord from the lock, and
passed on.
A few nights after I found it impossible to untie the cord, so I cut
it with my pocket-knife. The cord then became thicker and thicker
for several nights, but still my pen-knife did its work.
〈VARIOUS STRATAGEMS.〉

One night I found a small chain fixed to the lock, and passing
thence into Marryat’s bed. This defeated my efforts for that night,
and I retired to my own bed. The next night {21} I was provided with
a pair of plyers, and unbent one of the links, leaving the two
portions attached to Marryat’s arm and to the lock of the door. This
occurred several times, varying by stouter chains, and by having a
padlock which I could not pick in the dark.
At last one morning I found a chain too strong for the tools I
possessed; so I retired to my own bed, defeated. The next night,
however, I provided myself with a ball of packthread. As soon as I
heard by his breathing that Marryat was asleep, I crept over to the
door, drew one end of my ball of packthread through a link of the
too-powerful chain, and bringing it back with me to bed, gave it a
sudden jerk by pulling both ends of the packthread passing through
the link of the chain.
Marryat jumped up, put out his hand to the door, found his chain
all right, and then lay down. As soon as he was asleep again, I
repeated the operation. Having awakened him for the third time, I
let go one end of the string, and drew it back by the other, so that
he was unable at daylight to detect the cause.
At last, however, I found it expedient to enter into a treaty of
peace, the basis of which was that I should allow Marryat to join the
night party; but that nobody else should be admitted. This continued
for a short time; but, one by one, three or four other boys, friends of
Marryat, joined our party, and, as I had anticipated, no work was
done. We all got to play; we let off fire-works in the play-ground,
and were of course discovered.
〈FOUND OUT.〉

Our master read us a very grave lecture at breakfast upon the


impropriety of this irregular system of turning night into day, and
pointed out its injurious effects upon the health. This, he said, was
so remarkable that he could distinguish by {22} their pallid
countenances those who had taken part in it. Now he certainly did
point out every boy who had been up on the night we were
detected. But it appeared to me very odd that the same means of
judging had not enabled him long before to discover the two boys
who had for several months habitually practised this system of
turning night into day.
Another of our pranks never received its solution in our master’s
mind; indeed I myself scarcely knew its early history. Somehow or
other, a Russian young gentleman, who was a parlour-boarder, had I
believe, expatiated to Marryat on the virtues of Cognac.
One evening my friend came to me with a quart bottle of what
he called excellent stuff. A council was held amongst a few of us
boys to decide how we should dispose of this treasure. I did not
myself much admire the liquid, but suggested that it might be very
good when mixed up with a lot of treacle. This thought was
unanimously adopted, and a subscription made to purchase the
treacle. Having no vessel sufficiently large to hold the intended
mixture, I proposed to take one of our garden-pots, stopping up the
hole in its bottom with a cork.
A good big earthen vessel, thus extemporised, was then filled
with this wonderful mixture. A spoon or two, an oyster-shell, and
various other contrivances delivered it to its numerous consumers,
and all the boys got a greater or less share, according to their taste
for this extraordinary liqueur.
The feast was over, the garden-pot was restored to its owner,
and the treacled lips of the boys had been wiped with their
handkerchiefs or on their coat-sleeves, when the bell announced
that it was prayer-time. We all knelt in silence at our respective
desks. As soon as the prayers were over, one of the oddest scenes
occurred. {23}
〈EFFECT OF COGNAC.〉

Many boys rose up from their knees—but some fell down again.
Some turned round several times, and then fell. Some turned round
so often that they resembled spinning dervishes. Others were only
more stupid than usual; some complained of being sick; many were
very sleepy; others were sound asleep, and had to be carried to bed;
some talked fast and heroically, two attempted psalmody, but none
listened.
All investigation at the time was useless: we were sent off to bed
as quickly as possible. It was only known that Count Cognac had
married the sweet Miss Treacle, whom all the boys knew and loved,
and who lodged at the grocer’s, in the neighbouring village. But I
believe neither the pedigree of the bridegroom nor his domicile were
ever discovered. It is probable that he was of French origin, and
dwelt in a cellar.
After I left this school I was for a few years under the care of an
excellent clergyman in the neighbourhood of Cambridge. There were
only six boys; but I fear I did not derive from it all the advantage
that I might have done. I came into frequent contact with the Rev.
Charles Simeon, and with many of his enthusiastic disciples. Every

You might also like