100% found this document useful (2 votes)
405 views

Download Full React.js Book: Learning React JavaScript Library From Scratch Greg Sidelnikov PDF All Chapters

JavaScript

Uploaded by

kuangoaboni
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
405 views

Download Full React.js Book: Learning React JavaScript Library From Scratch Greg Sidelnikov PDF All Chapters

JavaScript

Uploaded by

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

Download the full version of the textbook now at textbookfull.

com

React.js Book: Learning React JavaScript


Library From Scratch Greg Sidelnikov

https://textbookfull.com/product/react-js-book-
learning-react-javascript-library-from-scratch-
greg-sidelnikov/

Explore and download more textbook at https://textbookfull.com


Recommended digital products (PDF, EPUB, MOBI) that
you can download immediately if you are interested.

Learning React js Learn React JS From Scratch with Hands


On Projects 2nd Edition Alves

https://textbookfull.com/product/learning-react-js-learn-react-js-
from-scratch-with-hands-on-projects-2nd-edition-alves/

textbookfull.com

Learning React Native Building Native Mobile Apps with


JavaScript 2nd Edition Bonnie Eisenman

https://textbookfull.com/product/learning-react-native-building-
native-mobile-apps-with-javascript-2nd-edition-bonnie-eisenman/

textbookfull.com

Deep Learning from Scratch 1 / converted Edition Seth


Weidman

https://textbookfull.com/product/deep-learning-from-
scratch-1-converted-edition-seth-weidman/

textbookfull.com

Reading and Mental Health Josie Billington

https://textbookfull.com/product/reading-and-mental-health-josie-
billington/

textbookfull.com
Police Leadership : Changing Landscapes Pauline Ramshaw

https://textbookfull.com/product/police-leadership-changing-
landscapes-pauline-ramshaw/

textbookfull.com

Ideas of Contract in English Political Thought in the Age


of John Locke 1st Edition Martyn P. Thompson

https://textbookfull.com/product/ideas-of-contract-in-english-
political-thought-in-the-age-of-john-locke-1st-edition-martyn-p-
thompson/
textbookfull.com

The Scorpion s Tail Nora Kelly 2 1st Edition Douglas


Preston

https://textbookfull.com/product/the-scorpion-s-tail-nora-kelly-2-1st-
edition-douglas-preston/

textbookfull.com

Military-Age Males in Counterinsurgency and Drone Warfare


Sarah Shoker

https://textbookfull.com/product/military-age-males-in-
counterinsurgency-and-drone-warfare-sarah-shoker/

textbookfull.com

Childhood and Schooling in (Post)Socialist Societies:


Memories of Everyday Life 1st Edition Iveta Silova

https://textbookfull.com/product/childhood-and-schooling-in-
postsocialist-societies-memories-of-everyday-life-1st-edition-iveta-
silova/
textbookfull.com
Drop Heating and Evaporation Analytical Solutions in
Curvilinear Coordinate Systems Gianpietro Elvio Cossali

https://textbookfull.com/product/drop-heating-and-evaporation-
analytical-solutions-in-curvilinear-coordinate-systems-gianpietro-
elvio-cossali/
textbookfull.com
React.js Tutorial Book
React is definitely one of the hardest things I had to learn from the pool of JavaScript libraries. In part, it is
because it assumes knowledge of so many other things associated with professional web development. Namely,
Node.js, NPM, mastery of babel command line tools, EcmaScript (5 and 6,) JSX and possibly WebPack.

This book also makes an assumption. That you're completely new to React programming. It creates a challenge
for me as the author, because it's my responsibility to speak about React in a way that is still meaningful, without
overwhelming you with large blocks of code that look complicated and hard to follow.

Having said this, my strategy for the presentation format of this book follows a simple pattern of mixing
explanations with simple code examples. Primarily, this book is a narrative designed to gradually delve into
understanding the React library.

I'll just put it out there right now that this book alone will not be enough to become an expert React programmer.
No publication about React can claim this, due to sheer scope of principles you need to understand in order to get
going and start writing real applications with React. Then there is also syntactical differences between EcmaScript 5,
6 and soon 7. For this reason React may turn out to be one of the most unusual learning experiences you have ever
had when it comes to JavaScript.

But breaking through the hard parts is worth the battle. And I hope this book will prove to be practical in
accomplishing this task.

Written and edited by Greg Sidelnikov


[email protected]
Table of Contents

A Note From the Author2

Main Roadblocks to Learning React4

Good Reasons for Learning React6

Reactive Programming8
Main Principles of Reactive Programming9
Gems and Working in the Mine12

The Essentials14

Special Props21

PropTypes22

Class Component Options23

Component Instances25
Properties25
Methods26

Gem 1 - React Components26

Gem 2 - Render Method28

Gem 3 - Virtual DOM and Bandwidth Salvation30

Gem 4 - Two Distinct Ways of Initializing a React Class32

Gem 5 - States & Life Cycles35

Gem 6 - Component Mounting39

Gem 7 - Node.js & NPM43

Gem 8 - JSX Walkthrough45

Lesson 1 - Writing Your First React Component49


JSX53
Props57
Function Purity58
Functional Components60
A Wolf in Sheep's Clothing62
Native Babel vs JavaScript Babel63
NPM63
Transpiling Source Code64
Lesson 2 - Nested Components65
Parent with a Single Child66
Parents with Multiple Children68

Lesson 3 - Handling Component Events69


Method 1 - getInitialState70
Method 2 - componentDidMount71
Method 3 - componentWillUnmount72

Example of a Complete React Application73


Creating Search List74
React Application74

EcmaScript 6
The var and let keywords77
The new const keyword82
Destructuring assignment83
For-of loop83
The Map object84
Arrow Functions84
What are Arrow Functions in JavaScript?90
Immediately Invoked Arrow Functions (IIAF)94
Backtick (``) Template Strings95
`string text`;95
`string text`;95
New Array methods96
A Note From the Author

Welcome to the introduction chapter of my book.


This is React Gems a book by Greg Sidelnikov.
That's me, the author!

First, thank you for showing interest in React Gems. This tutorial book was self
published by myself through my JavaScript web development newsletter. It will
walk you step by step through the process of setting up a development environment
and learning Reactive programming from start to finish.

As of 2017, what I call "reactive" programming has become an alternative way


of thinking about web applications. It provides software patterns that make your
web app extremely responsive to user input and generally feel faster to the end-
user (people who are using your application.)

When I was studying React it took me about 3 weeks for something to occur to
me. React is unlike any other JavaScript library I have ever programmed with. It
assumes a lot of previous knowledge. Because of this I had to write this book a
certain way, that gradually delves into the process of understanding it.

Studying React is not about just memorizing a few methods here and there and
using them as you wish. React itself is built on software principles that usually
become known only to professional software engineers who have worked in the
industry for a long time. This creates a challenge for authors like me who are trying
to explain React to JavaScript newcomers.

I chose to solve this problem by adopting a more fluid style of explanations that
border between discussions and source code and that make an attempt to create
balance between both. I didn't want to show long React programs and write a few
comments explaining what each line does. That would only complicate the learning
process. Instead, I broke down the narrative of the book into components (no pun
intended!) that deal with real problems you will be faced with when studying
React for the first time.

Programming with React library is a lot more than just learning about and using
React objects, components, states, props and methods. The entire book is
dedicated to explanations of what those are. Have you ever heard of props or
states in other libraries? States… probably, you did. But not so much props
(React's way of referring to "properties" of an object, which are in fact
arguments/parameters passed to React objects. It's a mystery of why they
decided to call this props. Because even what they represent comes from HTML
attributes, not properties.)

React makes understanding both (props and states) explicit requirements.


They're almost like sub-features that you absolutely must master in order to become
a versatile React library programmer.

It's the quirky details like these that requires previous experience with
JavaScript, without which (and explanations of which) it would be much more
difficult to learn React programming. Thankfully I am aware of this and the book is
written with all of this in mind. At times React assumes knowledge of software
principles not inherent to React library itself. The passages of this book will
gradually uncover them throughout the book as well.

This book is not a list of object names, methods and functions with side
explanations of what they do. You can look them up on Facebook's official React
documentation page including long lists and explanations of every single method.

Rather, the book will deal with the gradual learning process and understanding
of the said principles involved in React programming.

Before we begin I'd like to show you some of the things I discovered that.
Below you will see a list of the hardest things about learning React followed by
most important reasons why you would want to learn it.
Main Roadblocks to Learning React

Here, I'm going to make an attempt to speak of the commonplace difficulties faced
with learning React library from scratch. These are the ones that make learning React
not as intuitive as other far straightforward libraries you're already used to.

I'll try to do it without making React come off as a bad choice, because… all in all,
this is indeed a book about how to advance as a React programmer. However, if we at
least briefly talk about the hard parts now, it will make it easier to sink in later on as we
move forward.

1. New Design Pattern. New, and in many cases unfamiliar. If you're coming
to React from traditional pre-2015 JavaScript world of programming, it might
take time to adjust to modular a nd declarative design adopted by React
library. Sure, if you've ever worked on a large JavaScript application you
might have already dealt with long lists of .js files and treated them as
separate modules. But for large majority of programmers this isn't true. React
requires that we use modular design for maximum application management
efficiency.

2. J S X language throws a lot of people off. It's like writing HTML inside
JavaScript and at first it looks nothing short of bizarre, if you're encountering
it for the first time ever:

For example:

var divblocks = <div>


<div>Another nested tag</div>
</div>;

Like wait, what? Are you seeing what I'm seeing? We have just relentlessly
typed HTML into a JavaScript statement, without quotes surrounding the HTML,
and even have separated them using line breaks... and still got away with it.

JSX processor, which processes XML as if it's HTML and turns it into a valid
JavaScript statement we can toss around does all the dirty work for us behind the
scenes. In reality, this type of code is "transpiled" from XML (that looks like
HTML) to EcmaScript 5, so browsers can understand it. This means the actual
code the browsers sees will not even look this way. This is just for us, while we're
programming our app. But… we can write the code in this format without a hitch.

How it is used is discussed throughout the book. But basically, this format is
interchangeable with React component structure. What essentially you have just
created is actually a valid React component pattern.

For this reason, JSX is often used with React as a supplementary library. You
can create the same statement we've seen in example above, by writing it using
React methods. Using JSX is not a requirement, and you can get away without it.

However without it React programming becomes sort of like eating a pizza


without cheese. The two work together to provide a tasty experience, even if it
takes trial and error and time to learn how to bake the pie.

3. Babel & Transpiling code from EcmaScript 6 to an earlier version (ES5) is a


bit of an overhead and seems like an unnecessary thing to do as well. Because
eventually browsers like Chrome and Safari will have full support for ES6
and this process will become automatic anyway.

Babel allows us to write this code:

import someClass from "someClass.js"

And this will grab someClass class definition from the file someClass.js,
where it is defined. As of this writing, Chrome, Firefox and none of the other
browsers support ES6 import keyword.

However, babel allows us to start learning and writing ES6 code even now,
before official support is even rolled out in the modern browser. Until then it will
just "transpile" it back to ES5, behind the scenes, so that the code can actually run
in any browser today.

The good news is that installing babel plugins forces you to learn how to use
the command line tools. Something traditional JavaScript developers are usually
unfamiliar with. Which, I think the skill you should be learning anyway.

Using command line is a "must-have" skill in professional software


development environment (outside of personal projects in some arbitrary folder on
your Desktop). And... it's one of those extra steps that might potentially prevent
delving directly into Reactive programming, if not taken. As much of a hassle as it
may be.
Visit https://textbookfull.com
now to explore a rich
collection of eBooks, textbook
and enjoy exciting offers!
Good Reasons for learning React

1. It's fast. This is probably the top reason JavaScript programmers are looking
to start writing their applications using React library. Utilizing a virtual copy
of the DOM, it is designed to perform operations virtually before they are
rendered to the standard JavaScript DOM tree. This isn't just a numbers game.
It's surprising that moving UI operations to virtual DOM actually changes
how your application feels for the end-user. You've probably already started
noticing this phenomenon across the web on websites such as Netflix.

2. Modular design. React supports modular design that is often associated with
building large, scalable applications. The reason for this is the advent of
EcmaScript 6 specification that came out in 2015 which provides new syntax
that favors modular methodology, for example the require (ES5) and include
(ES6) keywords tie together not only files alone but assume class-based
relationship between objects. And even though as of this writing include
keyword is not supported in modern browsers (even Chrome) we can begin
writing modular programs by either using require, or transpiling our ES6 code
to ES5 (that almost all browsers do understand by now) before sending it to
the browser for rendering. When browsers catch up, we will no longer have
to transpile. When this takes place, React will become an even more common
library you'll see everywhere. Eventually, modular JavaScript program
design will become the norm with or without React.

3. Scalability. In React each HTML element is treated like a programmable


component that can be nested within other components. Child components
have parent components associated with them. The relationship between
parent and children components is established through something known as
props. Scalability of React programs is achieved by making each component a
conglomerate of HTML, CSS and JavaScript code.

4. Flexibility. React is more than just a UI view library as opposed to what you
will probably hear at first when you start figuring it out. And that isn't entirely
wrong. React gives us ability to create lightning-fast interactive components
that can be used as elements of our application. However, React's utilizes the
principle of render targets which allows you to send result of your code to
just about anywhere, included but not limited to front-end view.

5. Popularity among Employers. React was developed by programmers at


Facebook after years of studying web applications. More or less, it originated
from a set of proven software engineering philosophies. Although, many of
them most traditional JavaScript programmers will not be familiar with.
When you are learning React, you are learning computer programming
principles, not just a list of functions and methods, which is the case with
other libraries such as jQuery. In 2016 JavaScript has become the leading
language for front-end web development. Having React on your resume gives
you an edge over your competition if you're looking for employment in
software industry. The average Sr. JavaScript programmer in San Francisco
Bay Area makes $120-150K a year.
Reactive Programming

What is this reactive programming anyway? React is a small but powerful


library written in JavaScript. You can use it by including it on your web page by
using SCRIPT tag. Just like you would any other JavaScript library, like jQuery for
example.

If you are looking to be prepared for employment at an actual software


company, simply adding React to your web page isn't enough. It almost demands
that you understand other areas of web development that go beyond simple
JavaScript programming. The design of this book is dedicated to help nurture that
process.

By using React components, which will be shown throughout many examples in


this book, you will build an entire application. During many parts of this book I
will refer to building applications using the React library as "reactive"
programming.

Reactive programming is nothing more than a phrase made up to represent an


alternative way of thinking about building modern web applications. Reactive
programming is not inherent to programming using the React.js library itself. It's
just a methodology and it happens that React.js library certainly adopts it as core
philosophy.

What I mean by this is that it's the type of programming methodology that will
focus a lot on logical functionality of your program. Think about it as a more
advanced form of programming compared to working with DOM in JavaScript,
where each visual element of your app not only has events associated with them,
but can possibly contain custom programs that you will write yourself which will
determine their function.

While React is considered to be mostly dealing with the view areas of your
application, don't believe the myths that React is strictly the "view" in the MVC
(model-view-controller) pattern you're probably already familiar with. If not, just
know that the Model View Controller is a programming pattern that separates code
from the visual elements of an application. You've probably heard the phrase
"separation of concerns" in the past. But the point is that you can either install
React, learn and get used to its programming style and get a few UI elements
designed, or you can make it the reason you learn in-depth subjects of web
application development. The latter, is the approach I have taken while writing this
book.

I hope you enjoy this book, learn the React library and explore the possibilities
offered by modern software development that will train you for making real-world
web applications.
The Main Principles of Reactive Programming

Before we even go any further, it's important to mention what we are even
doing here. We can refer to programming with React as functional templating.
Not to be confused with functional programming languages. Here I simply mean
that your React components have a specific function to perform and that this is a
way to customize your components with unique capabilities. Whereas HTML
provides us with a set of elements (as HTML tags) that handle the layout of our
web application and provide interfacing with JavaScript code via attributes, React
is that… and a lot more.

React gives us ability to create compact blocks of code that tell us at a glance
exactly how your component will render on the screen all in one place, and often in
a single line of code. This gives tremendous opportunities for giving the
programmer an immense amount of control over making applications that create
visual elements and at the same time, give him (or her) the ability to program their
behavior.

React programs usually do not deal with separate CSS stylesheets. Interfacing
with the style is provided via virtual DOM. We'll see how that works later on in
the book.

Compared to traditional HTML, CSS and JavaScript approach, where we


would have to scout around the source code just to find different bits and pieces of
just one single element on the web page, React gives us a way to use
programmable templates.

In standard Ajax-based HTML applications, we're used to seeing code such as


demonstrated in the following example:

// HTML
<div class = "LoginForm">
<div class = "Name">
Enter username here.
</div>
</div>

And here is the counterpart jQuery ajax example:

// Ajax counterpart
$.ajax( { url: "/login.php",
data: { "username": "user1",
"password": "abfgh123" },

// login.php returned some data


success: function( msg ) {

// Adjust DOM data


$(".Name").html( msg );
}
);

This is a purposely simplified example. But you can see how even then, the
code is located in two separate blocks. One is the HTML layout definition. It is
almost like a reusable template for LoginForm with some dynamic functionality.

The second block of code is the actual program that executes an Ajax
statement. This line of code will load data from a PHP script based on the data
passed to it (username and password) and returns some type of a message in msg
variable.

Last, jQuery is used to modify the DOM by replacing the contents of div whose
class is Name with the message received from the script.

For a while this methodology worked just fine. Over the last several years, this
is how we're used to working with dynamic elements on a web page. But the
brilliance of React, is that it takes all that and gives us programmatic control over
the HTML and dynamic data, all packed in a neat render function:

render: function() {
return
<div>
{
This.state.name ? this.state.name :
<span>Enter username here</span>
}
</div>;
}

Notice how HTML and JavaScript code is intertwined without having to open
separate tags. Both exist within the same JavaScript statements and used almost
interchangeably without any problem. We'll get to how this is done in a few
moments.

Of course this isolated example makes almost no sense outside of being used in
a real-world application. But it shows a few important principles.

This react code that borrows its JavaScript-cross-HTML syntax from JSX
language gives us a means to know what the output of a dynamic element will look
like by briefly looking at the code. React here is trying to be everything to
everyone. And in some cases you will notice some patterns that almost feel like
bringing the back end logic into the front end.

The ternary operator ? : is used in this example. And basically, it's saying that
if the property name exists (not null or undefined) then we should output it. If it
doesn't exist, we should output generic "Enter username here" as the default
message.

This brings HTML template methodology to a different wavelength. Here, we


are designing and programming the component at the same time.
Gems and Working in the Mine

It's only the first chapter, and I am already delving into complexities of React
programming. However, let's get back to basics and break down some important
principles into smaller tutorial pieces first. It will help us later down the road.

Just like with my jQuery Gems book, we will start with a collection of "gems"
which is prerequisite knowledge that will provide quick insightful bits of
information required to move forward. Because the software industry is in
transitional times right now between EcmaScript 5 and 6, it will help us get
common quirks out of the way and stay focused on what's important when we get to
the rest of the lessons in the book.

If these gems are skipped, certain parts of the book later on might not make a
lot of sense. Especially if you've embarked on studying React as your first contact
with JavaScript programming.

But the gems is only one part of the book. They are designed to reduce as much
turbulence as possible and help you ease into the world of modern JavaScript
programming with a hint of reactive principles.

You simply must understand these principles before descending deeper into the
mine. The gems will sharpen your pick axe. The second part of the book will show
you the rest of the cave.

React on the Palm of Your Hand


To make your journey easier, I've included this section here representing each
separate aspect of a React program. Fasten your seatbelt and get ready to absorb a
lot of new principles! We're truly taking off into the world of React programming
now:)

This is a bird's eye view explanation going over the most important concepts
involved in building React programs. I already mentioned that learning React is
fragmented. And it assumes previous knowledge of advanced programming
patterns.

In this section, I'll try to break them down into reasonable chunks that can be
analyzed individually. And as we move forward, this will help you put the pieces
of the puzzle together. Think of the principles described here are the ideas fueling
the core engine of React.
Just because they are neatly outlined here, it doesn't mean that learning React
will be easy. But it certainly makes it easier to go through the rest of the book by
taking your time to familiarize yourself with them.
The Essentials

If you're familiar with jQuery, you've used the dollar sign ($) object for
selecting HTML elements and applying various operations on them.

But what is a similar building block of React when it comes to HTML


elements (not components.)? It must be the createElement method.

React.createElement(type, props, children);

And here are a few examples of how you would use createElement in practice:

let link = React.createElement('a', {href: '#'}, "Save");


let nav = React.createElement(MyNav, {flat: true}, link);

Here, we programmatically created HTML elements using React method


createElement. Then we have taken the created link element and placed it within
nav element to be one of its children.

Of course in this case link is the only child, but multiple links can be used as
well, as additional arguments separated by comma:

let link1 = React.createElement('a', {href: '#'}, "Save");


let link2 = React.createElement('a', {href: '#'}, "Delete");
let nav = React.createElement(MyNav, {flat: true}, link1, link2);

You can go like this forever, adding as many children as required by your
application.

Notice nav variable uses MyNav without double quotes. This is perfectly fine.
When we use custom elements (not the standard ones like a, div, table, etc…) that
we make up ourselves, we must use leading upper case letters. Therefore, the
navigation element is called MyNav. As long as we use the leading capital letter
React knows we're referring to a custom element. No need to use surrounding
quotes here.

In JSX it will translate to something like <MyNav />

Eventually with time as you develop your application, you'll arrive at full
Visit https://textbookfull.com
now to explore a rich
collection of eBooks, textbook
and enjoy exciting offers!
structures similar to one depicted in the following example. Note, that here it is a
little different as I am actually using React statements directly as children
arguments:

let nav = React.createElement(MyNav, {flat: true},


// start children of nav
React.createElement('a', {href: '#'}, "Save"),
React.createElement('a', {href: '#'}, "Load"),
React.createElement('a', {href: '#'}, "Delete"),
React.createElement('a', {href: '#'}, // AlertContaner
// start children of AlertCounter link
React.createElement('span', {alerts: 0}, "No Alerts"))
);

Note that some children are simple strings of text. They are used as text nodes
here. The stuff that goes in between the brackets of tags should also have a
representation. And that's what they're for. In this case children can be used as the
text supplied to the link's innerHTML, when they are not used for specifying nested
elements.

Also, here createElement is how you would create a React element in ES5
without JSX. I'll explain this in a moment. This is version ES5, for coding pre-
2015. While I advocate the use of ES6, I wanted to show you how it's done in ES5
first. Moreover, ES6 is backwards-compatible with ES5. So, this means that a lot
of the time how you write react programs will depend on your personal preference.

What's important to understand, for now, is that createElement takes three


arguments: type, props, children.

Here, type is the name of the element. For example A, H1, DIV, etc.

Then we have props, which are properties you pass to this component. Props
are not states, but they can modify states. We'll draw this distinction later in more
detail.

Finally, children are just hierarchical elements to be found within its parent
elements. Create chains of them and type them right into createElement function as
N-number of arguments at the end.

Another key that unlocks deeper understanding of React here is that all of the
code above has its equivalents in JSX. The two can be used interchangeably. This
is the part that actually is exciting, once you truly start understanding how it works.

So, while in ES5, you would use createElement function, in JSX (arguably its
common use is with the rest of ES6 syntax) you could create exactly the same
functionality by simply writing it out as follows:

let link1 = <a href = "#">Save</a>;

Now you see where I am going with this? JSX turns HTML into JavaScript
statements. Here link1 is object-like representation of the element which is exact
equivalent to React code we created earlier with createElement method.

And yes, link1.href will contain "#" by simply declaring it as JSX. Once I
realized that this is how it works JSX started to make a lot more sense and I
actually started to feel comfortable using it.

It's like a two-way road between HTML and JavaScript where attributes
automatically become properties.
And here is the more complex example, this time in JSX once again:

let nav = <MyNav>


<a href = "#">Save</a>
<a href = "#">Load</a>
<a href = "#">Delete</a>
<a href = "#">
<span alerts = "0">No Alerts</span>
</a>
</MyNav>;

We have just recreated virtual DOM using JSX language using a single
JavaScript statement! You can pass the value of nav around as a statement into
functions. It's almost like another way of creating a mini DOM structure.

Now you (hopefully) see that this is the very structure of virtual DOM in React.
It's like a secondary DOM we're going to be working with, changing, modifying,
editing, deleting and adding children from, etc.

We will update the actual primary JavaScript DOM object which is


responsible for visible elements in our application… but only when it actually
needs updating. None of the virtual DOM operations we're performing will be
associated with spending time updating the original DOM. And this is what
improves performance of React applications.

The best thing, React does this for us automatically. As a React programmer,
you are not required to understand how React does this internally. You just focus
on design of your application.

Note, of course if you type JSX code directly into your JavaScript application,
it will not even compile. You must be running JSX processor. To do this you
would usually initialize it from command line, so it constantly runs in the
background.

Babel has a JSX pugin. I also recommend learning how to make babel watch
your files. What this means is, you can set babel up so that it auto-transpiles your
.js files (and places them into "build" or "production" directory) automatically,
soon as the file changes. This babel functionality is called "watch". It first must be
enabled. I explain how to do this on Windows PC in my video tutorial:

React Tutorial on YouTube that helps you set up your development


environment, install Node.js, NPM, babel, JSX and help you start watching your js
files:

https://www.youtube.com/watch?v=tXaNvGcjEi0

You can get away with simply adding babel.js to your SCRIPT tag at the top or
bottom of your web page. JSX will transpile just fine. But this will significantly
slow down processing of your application. It should be used only for testing.

The video, on the other hand is only 58 minutes long, and if you're serious
about setting up a professional web development environment I recommend
breezing through it on 2x speed option in YouTube player which should only take
about 25 minutes. It's like a mini introduction course.

Finally, we're drawing this discussion to an end by showing that you can also
clone existing elements using cloneElement.

React.cloneElement(element, props, children);

It works in the exactly same way as createElement. Just pass an existing


element as element argument. Then, whatever props and children you pass to
corresponding parameters, will be merged into ones already available on the
original element. This is reminiscent of extending object functionality in traditional
Object-Oriented programming. Here, we're somewhat imitating OOP functionality.

Created elements can now be actually rendered to the DOM. You cannot render
to virtual DOM. The render function is the magick that takes care of this process
within React library internals. This is when our element "copy and pasted" from
our virtual DOM into the actual DOM that will be visible on the screen.

React provides render method on the main ReactDOM object as shown


below. In reactive programming ReactDOM is the second most important object
after React.

ReactDOM.render(reactElement, domContainerNode);

Here domContainerNode is the parent element on which reactElement will be


rendered, re-rendered or attached for the first time (mount.)

You can use render multiple times, if you need to update properties of the
component.

Here's what a real-life scenario might look like. In this example we're taking a
ReactElement and rendering it on a DOM node:

ReactDOM.render(
React.createElement("div"),
document.getElementById("container")
);
If you have an element already associated with a variable name, you can look it
up using ReactDOM.findDOMNode:

ReactDOM.findDOMNode( element );

This statement returns the DOM node associated with the given element. Note,
that this will only work only after element has been rendered to the DOM with the
render method. Until then, it is not findable in the DOM, even if it was already
created.
Special Props

Here we will briefly talk about special prop names, of which there are a few.
These should be treated almost like reserved keywords in JavaScript, except in
React. They all have a special meaning.

Children

The prop name c hildre n is automatically added to this.props by


React.createElement

className

This prop corresponds to the HTML's class attribute. You must use className
in your components/elements instead of name to avoid clashing with HTML's
reserved keyword.

htmlFor

Same as className only for the "for" attribute. htmlFor should be used in
your React element anywhere where you need to use "for" attribute.

key

The ke y prop uniquely identifies a ReactElement. It's used with elements in


arrays.

ref

The ref prop accepts a callback function which will be called:

1. With the component instance of DOM node on mount.


2. With null on unmount and when the passed in function changes.

style

The style prop accepts an object of styles, instead of a string. In React, there is
no mechanism for specifying CSS styles as a text string. This is one of the
limitations of using JSX.
Random documents with unrelated
content Scribd suggests to you:
wind, and feeling the awful numbness again creeping over them, but
with their eyes fixed upon the schooner’s light, that seemed so near
and yet so immeasurably far from them.
All at once Wolfe started up, exclaiming, “There’s another light!
see it, Breeze? A little one, between us and the flare. They’re coming
for us! They’re coming for us!”
It was a faint wavering light, like that of a lantern, and often, as
they watched, it disappeared, but always to appear again. Now it
seemed to be going away from them, and again finding their voices,
they raised once more the cry for help.
This time they fancied they heard an answer, and a little later
were sure of it. Half an hour of alternate fear and hope passed,
before, guided by their shouts, the rescuing party of four brave
fellows from the schooner reached them. They had made but slow
progress, dragging their dory over the broken ice, and not knowing
but that each step might plunge them into the water; but never
since hearing that first cry for help had they hesitated for a moment,
or thought of turning back.
The meeting between the rescued and the rescuers was too joyful
for description; but there was no time for words. The new-comers
had found an unbroken floe extending from the schooner, which was
made fast to the outer edge of it; but there was no certainty that it
would remain unbroken from one moment to another, and they
could not hasten back too quickly.
New strength came to Breeze and Wolfe with renewed hope, and
they were able to aid in dragging the dories back.
In less than half an hour later they were once more safe on board
the Vixen, and the whole crew was striving to see who could do the
most for their comfort, and show them how fully the brave deed
they had accomplished was appreciated.
They now learned that ever since darkness set in, those who came
to their rescue had held themselves in readiness to set forth the
moment they should find out in what direction to go, and that their
very first cries for help were heard and answered.
Breeze and Wolfe were readily thawed out by hot drinks and
blankets, so that they soon fell asleep, to awaken in the morning
feeling but little the worse for their hardships. With Hank Hoffer the
case was different. His hands and feet were frost-bitten, and besides
having a badly sprained ankle, he was so prostrated by what he had
suffered that he was confined to his bunk for many days, and never
wholly recovered from his terrible experience.
He never could tell exactly how he escaped to the iceberg, after
his dory had been crushed between it and the drifting cakes by
which he was surrounded. He was able, however, to describe in vivid
and forcible language his joy at sight of the schooner, his horror at
losing his foothold and falling into the deep crevice while trying to
signal her, and his fright when Breeze came sliding down on top of
him. Towards Breeze and Wolfe his gratitude knew no bounds. He
begged them to forgive him for the cruel tricks he had played upon
them, and was never afterwards tired of sounding their praises.
In this taste of arctic trials and sufferings the dorymates thought
they had met with adventures as strange as any they were likely to
encounter. But their trip was by no means ended, and the Banks still
held startling experiences in store for them, as they were to discover
ere many days had passed.
CHAPTER XIII.
LOST IN THE FOG.

For several days after that on which Hank Hoffer was rescued the
wind blew steadily from the south, driving the ice-fields far back
towards their northern home, but bringing in their place dense
masses of the almost equally dreaded fog. Fog is the ever-present
terror of the Banks, and hangs over them so constantly as to cause
the remark to be frequently made that in this latitude three hundred
and sixty-five days out of the year are foggy. Of course this is an
exaggeration; but it is true that hardly a day passes that does not
disclose a fog-bank rising above the horizon in one or another
direction.
This stealthy enemy is ever lying in wait for the fisherman, and
generally surprises him when he is least prepared for its coming. It
swoops down and envelops him in its blinding folds when he is out
in his dory, and when it again lifts, as though to mock him, he finds
himself alone on the vast waters, with no vessel in sight. It steals his
gear, and sends his craft drifting aimlessly hither and thither. Above
all, it leads swift-rushing steamers to where the fishing schooners
lie, and causes the great ships to spring upon them and crush them
down beneath iron prows, never to rise again.
The fog is terrible; but whether it comes or whether it goes, the
fish must be caught, for wives and children must be fed. So the
dories go out from the vessels, and if they never return there are
others to take their places. So accustomed does he become to its
presence that the fisherman hardly gives the fog a thought, until in
his turn it swallows him up, and he disappears forever.
The Vixen was now beset by a fog, sometimes so dense that it
settled down upon the water like a pall. Again it would lift, so that
her crew were able to set and haul their trawls, with some hope of
finding their vessel when the task was finished. It was dull,
dispiriting work, and in the midst of it an amusing incident, of which
Breeze McCloud was the hero, was hailed with delight by his
shipmates.
One night they were lying at anchor. The fog had lifted to such an
extent that it was not thought necessary to keep the fog-horn
constantly blowing. About midnight Breeze was turned out of his
bunk to go on watch. He had hardly reached the deck, and was still
rubbing his eyes, when suddenly he caught sight of a dim light. It
rose from the mist at about the height of a steamer’s mast-head
light, and was apparently bearing directly down upon them
amidships. He made one spring for the companion-way and another
into the cabin, yelling at the top of his voice,
“Turn out all hands! Steamer close aboard!” and snatching up the
fog-horn, he again rushed on deck, blowing it furiously as he went,
and followed by the startled crew.
Breeze did not even glance at the dreaded light again, so intent
was he upon getting all the sound he could from his fog-horn; but all
at once such a roar of laughter burst forth behind him that he
dropped the horn and turned indignantly to learn what it meant.
“Blow, sonny, blow!” cried one of the men between his shouts of
merriment. “You’ll have to do better than that to make the man in
the moon hear you.”
Then poor Breeze realized that what he had mistaken for a
steamer’s light was indeed the dim and watery moon struggling to
show itself through the upper edge of a fog-bank. There was
nothing for him to say or do, except to bear as meekly as possible
the jokes of his companions and the bursts of laughter with which
they greeted him whenever they met him the next day.
“BLOW, SONNY, BLOW!” CRIED ONE OF
THE MEN.

The trawls were set as usual the following evening, for in spite of
the fog the work of fishing was continued with considerable
regularity, and the next morning dory No. 6 went out with the others
in quest of its fare. It was customary in thick weather, while the
dories were absent, to keep the fog-horn constantly sounding on
board the schooner, so that they might be enabled to find her again.
On this occasion there was such a heavy sea running that unusual
care was necessary in the management of the dory, and its crew
were frequently obliged to swing her head to it to prevent her from
capsizing. After considerable difficulty they discovered their buoy,
and began to haul the trawl. In spite of the violent pitching of the
boat they were conducting this operation successfully, and had
nearly completed their task when, unnoticed by them, as their backs
were turned to it, a larger wave than usual came rushing towards
them.
It seemed to spring at the deeply laden dory, and lifted it so
suddenly that Wolfe, who was leaning over the gunwale, was pitched
head-foremost into the water. At the same instant Breeze, who had
been standing up, was thrown violently backward against the
opposite side of the boat, which was probably all that saved it from
upsetting. As it was, she shipped a quantity of water, and this, in
addition to the load of fish, sank her far below the limit of safety.
Her head, which had only been held to the wind by the trawl, now
swung off, and as Wolfe rose to the surface and clutched the stern
becket she had turned completely around, and was beginning to
drift.
Quickly recovering himself, Breeze went to his companion’s
assistance, and was endeavoring to help him into the boat, when
Wolfe gave a sharp cry of pain, exclaiming,
“I’m caught in the trawl! One of the hooks is in my leg! It’s
dragging me down! Oh, Breeze, help me!”
For an instant Breeze was horror-stricken; but his quick wit
enabled him to understand the situation at once, and also suggested
a remedy for it. Wolfe now formed the connecting link between the
dory and the trawl, which alone prevented it from drifting off before
the wind. The strain on his arms was so great, and the pain from the
hook in his leg was so intense, that he could not keep his hold on
the becket more than a minute longer. When he should once let go
he would instantly be dragged down beneath the dark waters.
While these thoughts were flashing through his mind Breeze had
picked up the buoy-line, cut it free from its keg, and passing the end
under Wolfe’s arms and around his body, had made it fast to the
after-thwart. He thus effectually fastened his companion to the dory,
and relieved, in a measure, the strain on his arms.
He next threw off his oil suit, his heavy outer clothes, and his
boots. Then, standing erect, with his sharp sheath-knife held
between his teeth, he sprang overboard and disappeared, head-
foremost, beneath the water, much as his dorymate had done a few
minutes before. In another moment the trawl-line holding Wolfe was
cut, and the terrible strain upon his leg was instantly relieved.
If Breeze had not been the splendid swimmer that he was, and
brought up from his earliest boyhood to feel almost as much at
home in the water as on land, he could not possibly have
accomplished this feat. Neither would he have been able to regain
the dory, which, taking a send of the sea, was at some distance from
him when he again rose to the surface. He only reached it after a
hard swim, and was breathless with his exertions by the time he had
managed to clamber in over the bow.
His first act was to lighten it, and cause it to ride more buoyantly,
by tossing overboard a quantity of the fish with which it was laden.
Then he helped Wolfe into the boat; and though the poor fellow’s
face was white with the pain he was suffering, he gave no
expression to it, but at once began to bail out the water that still
caused them great anxiety.
While he was thus employed Breeze was hard at work with the
oars, pulling in what he supposed was the direction of the schooner,
and keeping a sharp lookout for any waves of unusual size.
At last, when Wolfe had nearly finished bailing, he paused for a
moment in his task and said, “Breeze, it was splendid! I don’t believe
there was ever a finer thing done on the Banks.”
“Oh, pooh!” replied the other. “What would be the use of learning
how to dive and swim under water if you couldn’t do it when it was
necessary?”
“Yes, I know; it’s well enough to talk about doing such things
within reach of shore, but out here in the middle of the ocean, with
a sea like that running, makes it a very different matter. I say it was
splendid!”
“Wolfe, if you knew how like a coward it makes me feel now to
think of it, you wouldn’t speak of it again. I thank God that he put it
into my heart, and gave me the strength to do what I did. Above all,
I thank him that you are now with me in this boat, instead of at the
bottom of the sea; but I don’t want to talk about it.”
“And I say ‘Amen’ to your thankfulness with all my heart,” replied
Wolfe.
“By-the-way,” said Breeze, anxious to change the subject, “do you
hear anything of the horn?”
“No, I do not, and I don’t think I have heard it since we were
hauling the trawl,” exclaimed Wolfe, with a startled air, while an
anxious expression swept over his face. “Let’s listen a minute.”
Breeze stopped rowing, and they listened until he was again
obliged to use the oars to head the dory towards another big sea
that he saw approaching; but they heard no sound, save the moan
of the wind and the rushing of the waters on all sides of them.
It came upon them both like a shock, the terrible thought that
they were lost on that wild sea, and in a fog so dense that they
could not see fifty feet in any direction. Each saw by the other’s face
what he was thinking, but neither of them had the heart to put the
thought into words.
“I don’t suppose," said Breeze, at length breaking the silence,
“that there’s any use in rowing so long as we don’t know in which
direction the schooner lies."
“No,” replied Wolfe, “I don’t suppose there is. We had better make
a drogue and get it overboard, to hold her to the wind and keep her
from drifting as much as possible. Then we’ll fix ourselves as
comfortable as we can, until the fog lifts and we can catch sight of
the schooner again.”
Neither of them would admit in words that they did not expect the
fog to lift shortly, and that the schooner would still be in sight when
this happened. They both knew, however, that it might enshroud
them for days, and that they had but a slight chance of ever seeing
the Vixen again.
They made a “drogue,” or drag, by fastening an end of the buoy
rope to the bow of the dory, and the other to a couple of their trawl
tubs, which they then dropped overboard with the trawl anchor
attached, to serve as a weight. The tubs filled and sank until their
upper edges were on a level with the surface of the water. In this
position they acted as a floating anchor to the dory, which tailed off
from them at once and rode head on to the wind and sea.
“Stow the oars snugly,” said Wolfe; “we must not lose them
whatever happens. Then, I suppose we might as well toss the rest
of these fish overboard, though it seems a pity, doesn’t it?”
“Yes, and I’m afraid we’ll be sorry for it when we get back to the
schooner; but here goes,” and Breeze began to toss the fish
overboard vigorously.
When this job was finished, and the dory rode the seas much
more easily than she had done, Wolfe said,
“Now that you’ve made things snug and ship-shape, old man, will
you help me a bit with this beastly hook? It’s hurting me more than
a little.”
“Oh!” cried Breeze in a tone of pitying remorse. “Why didn’t you
speak of it sooner? It was awful to leave it in there all this time.”
“Had too much else on hand. It couldn’t get away, and I knew
we’d find it right there whenever we got ready to attend to it,” said
Wolfe, with an attempt to relieve the anxiety of his friend by making
light of his own sufferings.
Each of these two brave young spirits was intent upon presenting
a cheerful front to the other, while hiding its own anxiety and
forebodings, but neither of them was for a moment deceived as to
the nature of their situation.
As carefully as possible, Breeze first cut away the small portion of
line that still remained attached to the shank of the hook. Then,
after cutting little slits in them and clearing them from it, he drew off
Wolfe’s wet lower garments. The hook was fastened into the calf of
the right leg, and had torn the flesh cruelly. Now, while Breeze
could, if necessary, bear any amount of pain himself, it made him
faint to inflict it in cold blood upon others. So, when Wolfe said, “It
looks as if you’d have to cut the beggar out, old man,” he replied, “I
can’t do it, Wolfe! I haven’t the nerve.”
“Then I must,” answered his companion; and without a moment’s
hesitation he reached down, and with one powerful wrench tore the
hook from his leg and flung it overboard. “That’s a good job quickly
done,” he said, laughing at the other’s pale face. “Now if I only had
something to bind it up with!”
For a moment they could think of nothing suitable, for all their
garments were woollen. Then Breeze remembered his silken neck-
handkerchief, and hastily pulled it off. As he did so it caught on the
slender chain that he always wore clasped about his neck according
to the promise he had given his mother, and the golden ball
attached to it was brought into view.
Wolfe had never before seen it, and as he tightly bandaged his
wounded leg he asked Breeze what it was, and why he wore it. In
answer Breeze told him all that he knew concerning the ball, not
forgetting the encounter with the New York jeweller who had
opened it and then closed it again without allowing him to look at its
contents.
Wolfe was greatly interested in all this, and examined the locket
closely, in the hope of discovering its secret fastening, but without
success. For some time they occupied their minds, and kept
themselves from thinking of their unhappy situation, by speculating
as to what it contained. They wondered who had first clasped the
chain around the boy’s baby neck, and Wolfe declared that Breeze
was undoubtedly a lost prince, who would some day come into his
kingdom. He begged him not to forget his old dorymate when that
happy event occurred.
The word “dorymate” recalled them to their present surroundings,
and looking up, Wolfe said, “Well, there doesn’t seem to be any
prospect of the fog’s lifting yet a while. I wish it would, though, in
time to let us get back to the schooner for dinner, for I’m awfully
hungry. Speaking of dinner, have we got a bite of anything to eat
besides the raw fish we threw overboard?”
At another time Breeze would have laughed heartily at this Irish
bull, but now he only answered by going to the dory’s little stern
locker and drawing from it his oil-cloth provision-bag. A glance at its
contents assured him that they were all right, and he exclaimed,
joyfully,
“Here are two dozen large biscuit, and they’ve kept dry!”
“How about water?”
“I looked after that this morning, and the keg’s full of fresh water.”
“Then,” said Wolfe, “we’ve every reason to feel very grateful that
we’re so well off; and if we only had a compass we would head for
the coast of Newfoundland, and row to it, too, barring bad weather
and accidents, before our provisions gave out.”
“Yes,” said Breeze, “we’ve certainly got provisions enough to do it
with, for if each of us eats one biscuit a day, they will last us twelve
days.”
“Couldn’t we take two a day, and make it six days?” suggested
Wolfe.
“How would you like to eat three a day, one each for breakfast,
dinner, and supper, and call it a four days’ supply?” asked Breeze.
“Faith! I believe I could eat a dozen of them now, and then wish
for the rest without trying, I’m so hungry. But say, Breeze, how long
would they last us if we took three apiece the first day, two the
second, one the third, and then began and did it all over again?”
Thus talking, and in slowly eating two of their precious biscuit,
they managed to pass several hours, at the end of which they were
gladdened by a ray of sunlight. The fog was lifting. Starting up, they
eagerly scanned their widening horizon, which now extended for
some miles on all sides of them. To their bitter disappointment, they
could see no sign that any other human beings had ever floated on
that dreary waste of waters.
Shortly before sunset the fog settled down again, thicker than
ever; and lying down in the bottom of their boat, the dorymates very
nearly abandoned themselves to despair. Finally, huddling as closely
together as possible, for the sake of what warmth they could thus
obtain, they both fell asleep.
In his sleep Breeze dreamed that he was sailing a boat into
Gloucester harbor, but that instead of looking out for the familiar
landmarks, he was steering her by compass. He dreamed this same
thing over and over, until at last he awoke with it strongly impressed
upon his mind.
It was night, and intensely dark, while the wind moaned
mournfully above the dashing waters. Breeze had no idea of the
time, nor how long it would be before daylight. While he was
wondering about this he became conscious, to his great surprise,
that in his hand he held the golden chain and locket that had been
about his neck. His surprise was, moreover, quickly changed to
amazement when he felt that the ball was open.
CHAPTER XIV.
THE SECRET OF THE GOLDEN BALL.

It seemed to Breeze as though daylight never would come, as he


lay there holding the open locket in his hand and wondering about
it. How had it come open? and what did it contain? He was adrift in
a fog, far out at sea, in a frail open boat. He was wet, cold, and
hungry. His situation was about as uncomfortable as can well be
imagined; but all this was lost sight of and forgotten in the thoughts
aroused by that golden ball, which during his sleep he must have
taken from his neck, and which had so unaccountably been opened.
It was the visible evidence of the great mystery of his life, that he so
longed to solve, and in his curiosity he wished for the daylight only
that he might see what it contained. He hoped Wolfe would wake
up, that he might talk of all this with him; but he would not disturb
him, and after a while he, too, fell asleep again.
When Breeze next awoke it was early morning, and daylight was
sifting faintly through the fog. Wolfe had been aroused some time
before by the pain of his leg. He had just finished attending to the
wound as well as he was able, and was replacing the bandage.
The moment he noticed that Breeze had opened his eyes, he
exclaimed, “Good-morning, dorymate! We seem to be in luck, as
usual.”
“How?” asked Breeze, wonderingly.
“How! Why, don’t you notice that the wind has gone down and the
sea is getting smooth? We have had a pretty comfortable night, and
I shouldn’t wonder if the sun drove away this beastly fog before
long, and shone out warm and pleasant. Then we must surely sight
something, out of all the vessels that are cruising on the Banks.”
“That’s so!” said Breeze, quite cheered by this hopeful view of the
situation. Then, bethinking himself of the wonderful event of the
preceding night, and anxious to add his bit of pleasant intelligence,
he continued, “And best of all, Wolfe, the ball is open.”
“The what?” asked Wolfe, greatly puzzled for the moment to know
what his companion meant.
“The ball! The golden ball that I wear around my neck, and that
we were looking at yesterday.”
“You don’t mean it!” exclaimed the other, now greatly interested.
“How did you get it open? What’s in it? Where is it?”
“I don’t know how I got it open, and I don’t know what is in it
because it was too dark to see; but here it is.”
With this Breeze withdrew the locket from the bosom of his flannel
shirt, into which he had instinctively thrust it for safe-keeping when
he found himself dropping off to sleep, and they both bent over it
eagerly.
One half had swung back from the other on a pivot, by which the
two sections were still held together. After a single glance at it,
Wolfe gave a shout.
“A compass, by all that’s wonderful!” he cried. “The very thing
we’ve been wanting, above all others! Well, old man, any one who
says we are not in luck now doesn’t know what he’s talking about,
that’s all!”
One side did indeed hold a small but perfect compass, the
daintiest that was ever seen. Its freely moving card was a thin plate
of gold upon which were enamelled the four cardinal points and a
coat of arms. The latter consisted of a blue shield with a diamond,
cut in the form of a star, upon which the card was pivoted, in its
centre. On the shield, above the star, and in the lower corners were
three devices, which Breeze thought might be pyramids, and which
Wolfe called volcanoes. Above the shield was a closed helmet, and
beneath it, in letters of gold, the motto, “Point True.”
As Wolfe repeated this over to himself, his face wore a puzzled
look. “‘Point True,’” he said aloud; “I have certainly heard that
before, and I wonder where?” Finally he satisfied himself that he
must have read it in some book, and gave the matter no further
thought.
In the other half of the ball was a second golden plate on which
was enamelled the same coat of arms, with the only difference that
the central star in this case was formed of a pearl. A spring, which
they did not discover for some time, slipped this plate aside, and in
the cavity beneath it the boys saw three tiny locks of hair, of which
one had evidently been cut from the head of an infant. On the under
side of the plate was engraved “Merab to Tristram,” and Ruth’s
answer to Naomi, “Whither thou goest, I will go.”
Breeze could not help feeling somewhat disappointed when he
found that this was all. Although the ball had yielded up its secret, it
had in reality told him nothing. It had merely given a new direction
to his curiosity. Who were Merab and Tristram? To whom had the
locks of hair belonged? The only satisfactory features of its
revelation were the coat of arms and the compass. The former might
at some future time be located, while the latter could be immediately
used.
This thought had also come to Wolfe, who had rejoiced at the very
first sight of the little vibrating card, and who now said,
“Let’s have breakfast right off, Breeze, and then start for Nova
Scotia. I’ve been thinking the situation over, and though I believe we
are somewhat farther away from Nova Scotia than we are from
Newfoundland, we’ll stand a better chance of falling in with some
sort of a vessel by steering west than if we headed to the north. So
what do you say to laying a course due west, and sticking to it,
taking turns at the oars all day?”
“I don’t care much which way we go,” answered Breeze; “but I
think it will be much better for us to row than to lie still, because it
will at any rate occupy our time and keep us warm.”
“All right, then, west it is; and I wish the cook would hurry up
breakfast so that we could make a start. I’m not only awfully hungry,
but I’m in a great hurry to get to Nova Scotia.”
The cheerfulness and flow of spirits by which this Irish lad
managed to sustain both his own and his dorymate’s courage were
wonderful. They never flagged, and from the first to the last of that
memorable voyage his constant effort was to make the best of
everything, and turn every trifling circumstance to account for the
purpose of provoking a smile or inspiring fresh hope.
The two biscuit which, washed down with a swallow of water from
the little keg, formed their breakfast, were quickly eaten. Then the
drag to which they had been lying was taken aboard, and seizing a
pair of oars, Wolfe, who had insisted upon keeping first watch, as he
called it, began pulling vigorously in the direction indicated by
Breeze. The latter made himself as comfortable as possible in the
stern of the dory, with his gaze fixed upon the small compass that
he held in his hand.
In addition to his own inclination to look upon the bright side of
things, Breeze was happily influenced by his companion’s cheerful
view of their situation, and now he said, “So long as we have lost
the Vixen and found a compass, what a comfort the fog is!”
“Is it!” asked Wolfe, in surprise. “Well, I must confess I had not
quite taken that view of it. How do you make it out?”
“Because it keeps us all the time hoping for something to turn up.
It would be awfully discouraging to be able to see for miles, with
nothing but water to look at. Now we may come upon some vessel
at any minute.”
“That’s so. The skipper was telling the other night of some fellows
who were out four days in a fog without food or water, and who had
just given up in despair, when their dory was nearly capsized by
drifting afoul of the cable of an anchored schooner.”
“I remember a story my father used to tell,” said Breeze, “about
two men who were lost in a fog on this very Bank. They had been
out only about an hour when the fog lifted, and they saw the flare
their mates were burning for them. They rowed for it as hard as
they could pull, but the schooner was under way, and kept just
about the same distance ahead of them all night. The next day they
could still see her, with her flag at half-mast for them; but they
couldn’t get near enough for those on board to see them. After they
lost sight of her they were out two days longer, both of them bright
and clear. During that time they sighted and chased five more
vessels. Then the fog shut down again, and an hour afterwards they
were nearly run down by the schooner that picked them up. Now, if
they’d been in the fog all the time they would have taken things a
great deal more easy, and probably got picked up just as quick.”
“Yes,” admitted Wolfe, “that all may be very true; but I’m afraid
there’s another side to it. Hark! didn’t you hear a whistle?” he
exclaimed, resting on his oars to listen.
The next moment it came to them plainly, the hoarse warning
whistle of some great steamer. At first they could not locate the
sound; but as they heard it again, and this time much nearer, they
fixed it as coming from the direction in which they were heading,
and knew that it proceeded from some transatlantic liner, bound
eastward. Then they became filled with a fever of apprehension, of
mingled hopes and fears. What if she should run them down? What
if she should pick them up? What if she should pass without seeing
or hearing them? These were the questions they asked each other
over and over again during the few minutes that elapsed before the
vast, formless object rushed by them still concealed by the fog, but
so near that they could hear voices from her decks. They had not
been seen, nor were their frantic shouts heeded, if they had been
heard.
In deep, dejected silence they sat motionless, listening to the
sound of the whistle until it was lost in the distance. Then Wolfe
said, “That’s the other side to it.”
“Yes,” replied Breeze, “and it’s a pretty dark side to have to look at
too. If the fog had only lifted, ever so little, even for one minute, we
might be on board that steamer safe and comfortable now, on our
way to--I don’t knew where and I shouldn’t have cared. At any rate,
we wouldn’t be here, lost, starved, and drifting through a fog-bank.”
The boy’s tone was very bitter, and it showed the heaviness of his
heart.
“Take a biscuit, old man,” said Wolfe, sympathetically, “it’ll cheer
you up.”
For a moment Breeze tried to look angry, at what he considered
an ill-timed levity on the part of his companion; but the expression
of the other’s face changed his mood, and he laughed in spite of his
unhappiness.
“That’s right!” exclaimed Wolfe. “Laughing’s a sight more
becoming to you than crying, and whenever you ‘Point True’ to
yourself, it’s plenty of the first and little of the last you’ll be indulging
in.”
“But it is hard to bear such a disappointment. Just think how near
she came to us!”
“Faith! It might have gone harder with us if she’d come nearer. For
my part I’m just thankful she didn’t run us down entirely. Those
same steamers are the terrors of the Banks. I mind well the last trip
I was here in the old Walpus. We were lying to an anchor in a fog
every bit as thick as this, and minding our own business, when one
of them came rushing down on us. They paid no attention to our
shouting, or to our horn, and turned neither to port nor starboard;
but just came on tooting their old whistle for all other folks to get
out of their way. Well, sir, we were all in the act of piling over the
stern into the dories when she drove past within a handshake of the
end of our jib-boom, and we could see the scared faces of the
people on her deck looking down at us. She was that close that the
patent log towing behind her caught on our cable and parted its line.
We hauled it in the next day when we hove up our anchor. No, sir!
none of your steamers for me! They’re too careless and overbearing-
like, and I say we’ve just had a mighty lucky escape, and should be
thankful for it. Come, now, stand your watch like a good fellow, and
pull for Nova Scotia, or for some decent, easy-going sailing-vessel
that’ll pick us up.”
So Breeze took a spell at the oars, and thus rowing by turn, and
telling each other yarns of their own experience, or repeating what
they had learned from others to divert their thoughts, they passed
the second day in the dory.
The fog had not lifted for a single moment since morning, and
when darkness again shut down upon them it still infolded them in
its clammy embrace. Although the night was calm, they tossed their
drag overboard lest a wind should rise while they slept. Then, after
eating their scanty supper of a single biscuit each, they lay down,
hugging each other closely for warmth, and prepared to pass the
night in such comfort as their circumstances would permit.
Before they dropped asleep Breeze heard Wolfe say, as though
talking to himself, “We must have made something over fifty miles
to-day, and at the same rate we’ll soon reach the Nova Scotia coast
now.”
Breeze smiled at this too evident attempt to cheer him; for he
knew, as well as Wolfe, that they had not made more than twenty or
twenty-five miles at the most, and that the coast towards which they
were heading was still several hundred miles from them. Three more
days would finish their biscuit at the rate they had been eating
them, and even now he was so hungry that he felt they might as
well starve at once as to try and economize them any longer. Their
fresh water was already half gone, and altogether their prospect was
a very gloomy one.
The night passed uneventfully, but before daylight Wolfe was
awakened by an exclamation of dismay from his companion. “What
is the trouble?” he inquired, sitting up stiffly.
“The ball is closed,” answered Breeze.
“Closed?”
“Yes; it must have got pushed together somehow while I was
asleep, and I can’t get it open again.”
“And a good job, too,” said Wolfe. “Now we’ll have no excuse for
rowing this day, and I’m glad; for my back’s broke thinking of it.”
“But don’t you want to get to Nova Scotia?”
“Indeed, I do not! An out-of-the-way place like that? I’d prefer to
be picked up where we are by some craft that’ll take us into New
York, or Boston, or maybe Gloucester itself.”
An hour later the sun rose, and under its cheerful influence the
last trace of fog disappeared, and a perfect spring morning broke
over the sparkling waters of the Grand Bank. It was just such a
morning as would cause the New England birds to break forth in an
ecstasy of song, and Breeze almost expected to hear them as he sat
up in the dory and looked around.
His ears were not greeted by the songs of birds, but his eyes were
gladdened by a sight so welcome that his first joyful exclamation
was choked by his emotion.
Wolfe sprang up in alarm at the sound, only to see his friend
pointing with trembling finger to the southward. There, not more
than half a mile from them, he saw a square-rigged, deeply laden
vessel, rising and falling gracefully on the long swells.
The next moment Breeze had cut the line that held them to their
drag with a blow from his sheath-knife, and, under the impulse of
two pairs of oars, dory No. 6 was surging over the calm waters as it
had never before been driven in all its storm-tossed career.
The dorymates spoke no word to each other, nor looked around,
until they paused, breathless and panting, close beside the vessel.
Although there was not a breath of wind, they had feared that
somehow she might sail away and leave them. Now that there was
no danger of that, they sat in their boat and gazed at her curiously.
Her bottom was covered with sea-grass and barnacles, and she was
weather-beaten to the last degree, though her spars were all in
place and she still looked stanch and seaworthy. Not a human being
was to be seen on board of her, nor did their hail receive any
answer.
The strangest feature of the brigantine, for such she was, lay in
her sails and rigging. Instead of showing a cloud of light canvas, as
would naturally be expected in such weather, she was under a
double-reefed main-sail, single-reefed fore-topsail, and fore-staysail
only. Her fore-course was clewed up but not stowed, and the royal
was furled; but the topgallant-sail seemed to have been blown away,
judging from the few streamers of tattered canvas that still hung
from the yard. Her running rigging was either hanging at loose ends,
or tangled in the greatest confusion. To crown all, a ragged
American ensign drooped at half-mast, and union down, from her
main-peak.
NOT A HUMAN BEING WAS TO BE SEEN
ON BOARD OF HER, NOR DID THEIR
HAIL RECEIVE ANY ANSWER.

The boys pulled entirely around the vessel several times,


wondering at her condition, but still unable by their shouts to attract
the attention of her crew. On her stern they read her name,
Esmeralda, of Baltimore.
Finally Breeze spied a rope hanging over her side near the fore-
chains, and proposed that they board her by it. Having tested it and
found it strong enough for their purpose, they went up hand over
hand. Breeze was the first to clamber over the bulwarks and gain
her deck. It was absolutely deserted, and he walked aft while Wolfe
was making the dory fast.
There was something mysterious and awful about this apparently
deserted brig that caused Breeze to shiver and gaze about him
apprehensively. He walked as far aft as the quarter-deck, and as he
gained it a gaunt, pale-faced man came slowly up the companion-
way leading down into the cabin, and stood looking at him. Breeze,
too, stared for a moment, and then sprang towards the trembling
figure.
CHAPTER XV.
A WONDERFUL MEETING.

As Breeze came towards him, the white-faced man in the


companion-way, who was so weak and emaciated that he seemed to
have just arisen from a sick-bed, tried feebly to wave him back. The
effort was made in vain; for the next moment the boy had sprung to
where he was standing, thrown his arms about his neck, and, half
laughing, half crying in his excitement, was exclaiming,
“Father! oh, father! We knew you weren’t dead. We knew you’d
come back to us--mother and I did!”
“Gently, lad, gently. I’m not quite steady on my pins yet, and if
you don’t have a care you’ll pitch me down the steps,” answered
Captain McCloud, trying to speak calmly and to quiet the excited
boy. But tears stood in his eyes, and directly his weakness had
mastered him. He cried out, brokenly,
“God bless you, Breeze! God bless you, my boy! I’d thought never
to see you again, and in my heart I’d bidden you good-by, mother
and you. But I wasn’t reconciled to it. I couldn’t die without seeing
you. You’d not ask it, lad. You’ll not leave me again to the fever, will
you?”
Then, overcome by his emotion, the man who had been so strong,
but who was now so weak and wellnigh helpless, bowed his head
and sobbed like a child.
This pitiful sight, and the piteous appeal just made to him, almost
unnerved Breeze, but he controlled himself by a strong effort, and
led his father to a seat, at the same time speaking soothing and
loving words to him.
“No, father,” he said, “of course I’ll not leave you. I’ve come to
stay with you, and take care of you, and carry you into port, where
mother is waiting for us. Only you must hurry and get well, for it
would never do to go back to her sick and looking like this, you
know. It would frighten her to see you so.”
Just then, walking stiffly on account of his wounded leg, Wolfe
came aft in search of Breeze, and was filled with amazement at what
he saw. For once his ready tongue failed him, and he stood staring
at the little group in silence. He wondered what could have affected
them so deeply, and if they had ever met before, or whether he
were not witnessing the effects of a mild species of insanity, as
exhibited by the stranger.
“At any rate,” he said to himself, “I’ll not interfere with them, for
Breeze seems to have a quieting way with the old gentleman, and
maybe hearing another strange voice might send him off again.”
All at once his attention was attracted by the sudden appearance
of the most uncouth and altogether peculiar human face he had ever
seen. The head to which it belonged had just been lifted cautiously
above the cabin companion-way, and the great eyes, which seemed
to Wolfe to be wholly white, were rolling wildly at the sight of the
strangers. The face was the color of black ashes, the flat nose
expanded into a pair of enormous nostrils, while the lips were of
unusual thickness, even for a full-blooded negro. This strange face
was set off, and in a manner overshadowed, by a pair of most
remarkable ears. Not only were they large, but they projected
almost at right angles from the head, which gave them the
appearance of always being pricked forward with an air of extreme
attention or curiosity. Above and in front of these the head was
covered with a thick growth of kinky hair, which had been for so long
brushed, pulled, or otherwise trained forward that it surrounded the
face like a sort of a furry hood. On account of it some wag in the far-
away country from which this odd-looking individual came had called
him “Nimbus,” and this name had clung to him ever since. He was so
short as to be almost a dwarf, but his body was thick-set, and
powerful enough to belong to a giant. The length of his arms was
extraordinary, and so was the size of his feet, but his legs were so
ridiculously short that he waddled rather than walked. He was as
strong as two ordinary strong men, and at the same time he was
tender-hearted, obliging, good-natured, a fair sailor, and a capital
cook. He was a Guinea negro, from the west coast of Africa, but had
passed the greater part of his life in the galleys of sailing-vessels,
and had thus visited most of the principal ports of the world. He was
fond of occasionally returning to his own country, which he managed
to do about once in every two or three years. Such was the
individual who now appeared at the top of the companion-ladder,
and exclaimed,
"T’ank de good Lord, gemmen, you’s come at las’! Me an’ de
cap’n, we’se been habin’ a mons’rous hard time, an’ we’se mos’ gib
up. You mus’ scuse me, gemmen, fur not bein’ on de deck to receib
you proper an’ ship-shape, but I ain’t had no sleep fur more’n a
week, an’ I jus’ takin’ a nap. You see, fus’ de port watch on deck all
night, den de cook he busy waitin’ on de cap’n all night, den de
starbor’ watch he up all night, den de fus’ ossifer, den de secon’
ossifer, dey don’ get no sleep all night, an’ I is all ob um. Yes, sah,
ole Nim he ebberyt’ing but cap’n ob de Esmeral now. De res’ all dead
an’ go oberboard. De feber catch um. Sometime one, sometime two,
t’ree togedder. De las’ one, he de fus’ mate, die more’n t’ree day. De
cap’n here, he mos’ die, but ole Nim pull um troo; couldn’ be lef’
alone nohow. Where you’ ship, eh?"
As he asked this question Nimbus looked around with a perplexed
air, in search of the vessel from which he supposed these strangers
must have come.
Wolfe was delighted with this odd character, and now glad of a
chance to use his tongue, he told their story as briefly as possible,
and ended by saying that they were awfully hungry.
Nothing pleased Nimbus more than a chance to cook for
strangers; and, with a broad grin on his hooded face, he waddled
away towards the galley, saying,
“Dreckly, gemmen! dreckly ole Nim get you mons’rous fine
breakfus.”
In the mean time Captain McCloud had recovered his composure,
and now, to Wolfe’s amazement, Breeze introduced him as his father.
At the same time he said, “Wolfe Brady is my dorymate, father, and
next to you and mother, my dearest friend. We haven’t known each
other very long, but what we’ve been through with has made us
pretty well acquainted.”

“ME AN’ DE CAP’N, WE’S BEEN HABIN’ A MONS’ROUS


HARD TIME.”

“Yes, sir,” said Wolfe, “we met only about three weeks ago, but in
that time your adopted son has twice saved my life at the risk of his
own, and we have been in some rather tight places together. I don’t
mind saying, now that it is all over with and we are standing on a
good solid deck once more, that drifting around in that dory, through
the fog of the last two days, was about the meanest fix of them all,
and I hadn’t much hope that we were going to get out of it either.
I’d go through with all its suffering and anxiety again, though, for
the sake of being present at such a wonderful meeting as this. I
never heard of anything like it.”
“It is truly a wonderful meeting,” replied Captain McCloud, “and
there have got to be a great many explanations made before we
shall understand how it was all brought about. Certainly we have
been guided in marvellous ways. You said your mother was well,
Breeze?”
“Yes, sir, quite well,” answered Breeze, “and looking for you to
come in at any time.”
“So she hasn’t given me up yet! Bless the little woman! Well,
there’s a chance of getting there now. I didn’t think there was any
hope of it three days ago, when the mate died, and left Nimbus and
me alone on the old brig, and I too weak to lift a rope’s end.”
“Do you mean to say, father,” exclaimed Breeze, who had not
comprehended the true state of affairs before this, “that you two are
the only ones left aboard?”
“Yes,” replied the captain, sadly, “we have buried all the rest, and
are the only survivors of a crew of twelve souls.”
“That’s the reason, then, you’re under such short sail.”
“Yes, she was got under this canvas in a blow, two weeks ago,
while the mate and two others of the crew were alive, and still able
to work. Since then there has not been force enough on board to do
anything with them. Nimbus is as strong as an ox, and he can
manage the head-sails alone. I believe he got the course clewed up
too; but the poor fellow has had a hard time trying to steer, cook,
wait on me, keep a lookout, set the lights, ring the fog-bell, bury the
dead, and in fact do all the work of twelve men. He fell asleep last
night on the cabin floor, utterly exhausted. This morning I was going
to try and shift for myself, and let him have his sleep out. I was
about to look for something to eat when you came aboard. I’m
feeling hungry for the first time in weeks.”
“Faith, sir!” cried Wolfe, “it must be catching. I’m so hungry myself
that if starving’s any worse it would take a wiser man than I am to
point out the difference. And to think, Breeze, of the elegant biscuit
we left behind in the dory! If we’d only eaten them yesterday, and
had the comfort of them! Never mind, we’ll have them up after a
while for a dessert, like, for of all the sea-biscuit ever I tasted those
have the finest flavor. But here comes breakfast now, praised be the
cook!”
Nimbus was going to carry the breakfast down into the cabin, but
Captain McCloud said they had better eat on deck, on account of the
fever that had been in the cabin. “I tried to warn you, Breeze,
against coming too close to me when I first saw you,” he added,
“but you didn’t seem to pay any attention.”
“As if I could have, father, when I was so surprised and so happy!”
replied Breeze, reproachfully.
Never had a meal tasted better, or been more thoroughly enjoyed
by the dorymates than this one, and it seemed as though they could
not stop eating. Even Captain McCloud developed a wonderful
appetite for a sick man. He ate so heartily that Nimbus, who
waddled around them, his face beaming with pleasure, as he
brought them this thing or that, began to grow somewhat anxious
and exclaimed,
“Take care, cap’n; you’ ’tomach’s powerful weak yet, an’ you
mus’n’t s’prise um too much!”
“Which are you now, Nimbus, doctor or cook?” asked Captain
McCloud, smiling at the faithful fellow’s anxiety.
“I’se bofe, cap’n. De ship’s doctor and de ship’s cook am de same.
P’r’aps de cook tell you eat, an’ de doctor tell you not eat. You min’
um bofe, den you all right. You min’ de cook, you eat too much.
Berry bad! You min’ de doctor, you eat too little. Berry bad too! You
min’ ole Nim, you all right. Berry good!”
Wolfe was immensely amused at all this, and the negro’s comical
appearance, together with his earnest manner, caused the young
Irishman to roar with laughter. He declared that Nimbus had more
sense in his woolly head than half the white folks he knew, and that
if he were as good a doctor as he was a cook, he ought to be a
member of the Royal College of Surgeons.
“Don’ know nuffin ’bout no surgins, sah,” replied Nimbus, showing
the ivory of his teeth in a broad grin, and highly flattered by this
praise; “but if de young gemman’s ready for anodder cup ob coffee,
I’se got um a-bilin’ in de camboose.”[G]
“Will I have another cup of coffee? Of course I will! It’s the best I
ever tasted. I tell you what, Breeze, there’s nothing like drifting
around a few days without anything to eat to make a fellow
appreciate a meal like this.”
“We had the sea-biscuit,” said Breeze.
“Yes, sea-biscuit! But what did they amount to? Dry, tasteless
things! I’d almost as soon eat so many chips,” exclaimed Wolfe, in a
scornful tone, as he finished the last mouthful of a hot buttered roll.
“Then you are not going to have them up for a sort of a dessert?”
“Dessert! I should say not. I hope I’ll never have to see one, much
less eat one again. They would always remind me of drifting through
a fog-bank in an open dory.”
All of which goes to show how very differently a hungry man and
a well-fed man may view the same object.
The sea still remained unruffled by a breath, and after breakfast
Captain McCloud said, “So long as there’s nothing we can do until
we get some wind, we’ve a chance for a yarn. If you’d like to hear
about it I’ll tell you how I happen to be aboard this brig, and how
she got into the sad condition you see her in now.”
As both Breeze and Wolfe expressed the strongest desire to hear
the captain’s story, he related it to them as follows:
“You remember, Breeze, when I left home in the old Sea Robin last
October for the Banks I said that if all went well I’d be back in time
for Christmas?”
“Yes, sir, I remember.”
“Well, we made a fair trip, but did not fill up as fast as I had
hoped we would, so that it got to be pretty near Christmas-day
before we saw our way clear to picking up our anchor and heading
for Gloucester. By-the-way, have any of the Robin’s crew ever turned
up?”
“No, sir; not one of them. You were reported as seen on the 15th
of December, but since then not a word has come from you until this
day.”
"Poor fellows! they’re long since gone, then. Well, as I was saying,
we were all ready to start for home the day before Christmas, when
there came on such a gale of wind as I’ve rarely seen in these
latitudes. By night it was a hurricane, and such a sea was running
that it seemed as though each wave must swallow the schooner as it
came rushing-down on her. We were hove-to under a three-reefed
foresail, and the riding-sail with a bag-reef tied in it. About nine
o’clock in the evening, I’d been on deck so long, and was so
drenched and chilled, that I stepped into the forecastle to get a cup
of coffee. There was one other man there, poor Dick Simonds--you
remember him, Breeze--and the cook. The rest were either on deck
or in the cabin.
"I had just braced myself between the foremast and the edge of a
bunk, and was reaching for the coffee, when the vessel seemed to
give a great leap in the air. When she dropped it was on her beam
ends, and I could feel her settling down. The cook got out someway,
how I don’t know; but Dick was met by the water pouring in the
companion-way. He pulled the slide to keep it out, thinking she’d
right in a minute if she didn’t fill first.
"At the first shock I was so braced that, lying on my back as I
was, I couldn’t move, and when I did get right side up, there we
were, Dick and I, shut up like two rats in a trap, and the schooner
was bottom side up.
"Dick stood it as long as he could, which I suppose was some time
the next day. By then it had got so quiet overhead that we judged
the storm had gone down. At the same time we knew our air must
be escaping, for we could feel the water slowly but surely rising in
the forecastle. The rats were becoming troublesome, too, and
swarming over us. Though we couldn’t see them, we managed to
catch and drown quite a number of them.
"At last Dick said he couldn’t die but once anyhow, and that he
was going to make a try for one more breath of fresh air and one
more sight of God’s blessed daylight. He succeeded in smashing off
the companion-way slide, and a faint light came in through the
water, so we knew it was day. I didn’t remember till afterwards that
it was Christmas-day, and I’m glad I didn’t.
"Dick’s plan was to dive through the opening with the hope that
he’d clear the rigging and sails underneath it some way or another. I
tried to dissuade him from trying it, and pointed out how slim his

You might also like