React - Js Book - Solid Understanding of A Hard To Learn The Basics of ReactJS Programming - Greg Sidelnikov
React - Js Book - Solid Understanding of A Hard To Learn The Basics of ReactJS Programming - Greg Sidelnikov
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.
The Essentials 14
Special Props 21
PropTypes 22
Class Component
Options 23
Component
Instances 25
Properties 25
Methods 26
Gem 1 - React
Components 26
Gem 2 - Render
Method 28
EcmaScript 6
The var and let keywords 77
The new const keyword 82
Destructuring assignment 83
For-of loop 83
The Map object 84
Arrow Functions 84
What are Arrow Functions in JavaScript? 90
Immediately Invoked Arrow Functions (IIAF) 94
Backtick (``) Template Strings 95
`string text`; 95
`string text`; 95
New Array methods 96
A Note From 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.
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.
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.)
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.
2. JSX 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:
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.
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.
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.
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.
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
// HTML
<div class = "LoginForm">
<div class = "Name">
Enter username here.
</div>
</div>
// Ajax counterpart
$.ajax( { url: "/login.php",
data: { "username": "user1",
"password": "abfgh123" },
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>;
}
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.
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.
And here are a few examples of how you would use createElement in
practice:
Of course in this case link is the only child, but multiple links can be
used as well, as additional arguments separated by comma:
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.
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.
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.
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.
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.
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:
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.
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.
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
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
ref
style
It might feel a little awkward at first but this style actually adapts much
better to the overall scheme of React programming.
PropTypes
React has a special property called PropTypes. Typechecking is its
primary purpose. As your app becomes large in size, type checking can
help catch various bugs.
ReactComponent.propTypes = {
name: React.PropTypes.string
};
any
array
bool
element
func
node
number
object
string
Class Component Options
We'll speak about components a lot more throughout the rest of the book.
They are the building blocks of your react application. But remember
that this is "React on the Palm of Your Hand" section! Let's briefly
overview the full scope of a React component, its options and methods
available by default in React library. Components are defined by
createClass method existing on the main React object:
displayName: 'MyComponent',
render: function() {
// Once rendered, let's return a newly created element
return React.createElement( /* … */ );
}
});
Component Options
Components hold the propTypes object and two methods that return an
object:
Lifecycle Methods
1. componentWillMount
2. componentDidMount
3. componentWillReceiveProps
4. shouldComponentUpdate
5. componentWillUpdate
6. componentDidUpdate
7. componentWillUnmount
In addition to these methods, of course you can also add your own
custom functions, depending on what your component is supposed to be
doing.
Component Instances
Component instances are the instantiated objects from the class
representation we've just taken a look in the previous section. Here are
a few hints as to their implementation:
Gems
And just like the first time you were learning about regular DOM back
in the day and realized that each HTML element (such as P, DIV, TABLE
and others) is actually an object in a long tree-like chain of the Object
Model, think of react components as visual areas that are also tied to
some sort of software function. This time, this functionality will be
custom-determined by you and the requirements of your application.
From these fundamentally basic principles of React, you can now see
why Facebook and Instagram love using it. It's lightning-fast, it helps
break down feed-like elements into software blocks composed of
components which are just bundles of CSS, HTML and JavaScript code.
This design model is a lot more in touch with app-like behavior rather
than just informational websites that use table-like layouts.
Components are hierarchical. They can be children of other
components. For the most part, components are tailored for reuse in
your application. They contain patterns of code that can be adapted to a
wide variety of cases. React code usually follows a pattern of creating
chains of these components that work one within another, while
retaining fast rendering speed and flexibility.
Gem 2 - Render Method
Chances are that to some degree, you've already split up your app into
compartments when you were building regular HTML-JavaScript
applications. Then, you used Ajax events to populate each view
separately, based on what type of data changed in each HTML element
cell.
But React takes this approach one step further by requiring render()
method. The render method must be attached to each React component
you create. There is no way around it. It's part of the pattern that React
components demand that is being used.
Even though React is so much more than the view layer - making the
render method explicit to programming with React, is the reason why
React is often considered to be primarily a view-based library. We will
see why this is true throughout the book, but also why this isn't entirely
true.
While you can use any third party library in addition to React, for
example database IO libraries, React still offers a lot in the way of
custom programming that goes behind the view elements. In fact, it
demands that you understand how these programming principles work.
The method render() which is usually attached to the React's own
"virtual" DOM is the method that will be executed when your
application is loaded into the browser for the first time. And
consequently, only when the data in the element it represents should be
updated. However, this is where it gets interesting. Until the render
method is called, the react's component isn't even "mounted" to the
actually JavaScript DOM, nor will it be displayed. And it's possible to
create React components without mounting them. We'll cover mounting
in greater detail in Gem 6.
We know that render triggers an update of the data set (or state of the
component). But when should the data be updated? This will depend on
the type of data shown in your components but also a few generic
function that are responsible for updating it at key times while it's
being used. Later in the book we'll get to the functions responsible for
giving us control over these events.
Notice that in EcmaScript5 the constructor keyword does not exist. And
this is why in this case React provides getInitialState function. If you
are writing your app in ES5, you should use this method to initialize
default state of your component.
We'll get to states in just a moment. Because it's such an important
subject. States are tied to react components. You should draw a mental
association between the component and its state while planning your
application. Each component is responsible for having a state.
Above we demonstrated ES5 syntax. I won't tell you which one of the
two you should use.
Eventually ES6 is going to become the newly adopted standard within a
few years, but many programmers still prefer ES5 formatting. Both still
work as JavaScript supports ES5 as a subset of ES6 for compatibility
with future applications.
If this works for you, use EcmaScript6 as demonstrated below, now
using the new keywords not available available in ES5: class, extends,
super and constructor:
It's same thing, except using ES6 syntax. If you're coming from Java, C#
or C++ languages, you might be more familiar with this class creation
syntax and might prefer it over the outdated ES5 format.
It's just the period of time we're faced with right now, as JavaScript
specification matures. Until browsers fully adopt EcmaScript 6,
studying this syntax format gives you an advantage of learning something
that isn't yet in wide use, but that will definitely become the next
standard over the next few years.
The Life Cycle of a React component has a lot to do with states. And
React provides several default methods that help us write efficient
applications. These methods are briefly outlined below.
Each component will usually control its own states via following helper
methods. They are designed to modify or update component's state at a
unique time during the application flow or component's Life Cycle.
All of these methods are attached to the component's object like shown
below. This is just a brief example demonstrating the placement of these
methods within your React object.
displayName: 'MyComponent',
});
That's a whole lot of Wills and Dids. But what do they all mean?
These methods are like the command center of our component!
Below I'll provide brief descriptions for which events during the
lifetime of a component each one of these methods is responsible for.
var component =
React.createElement( ComponentDefinition );
React.render(component, container);
The render method mounts this component to the DOM. The reason
this process is referred to as mounting is similar to virtual hard drives.
If you've ever mounted a virtual CD-Rom or hard drive on your
computer, you know how it works. The hard drive doesn't physically
exist. For the same reason, this is why this type of software is called
virtual hard drive. Or virtual CD-Rom. And this is why virtual drives
have features like "mount this drive."
Likewise, this is the same principle behind virtual DOM in React. Until
it is mounted, it cannot be operated upon. This is what makes React so
much faster than regular DOM operations. And this is probably one of
the top reasons for using React in the first place. React stores a fast in-
memory representation of the DOM.
But this virtual DOM is not even associated with the JavaScript's DOM.
It exists side by side, and renders into the actual DOM on the screen
only when it becomes necessary. Usually, when the component
representing an element is actually updated with new incoming data.
Essentially, React is designed to update components on the screen only
when they need to be. Another advantage of doing it this way is that it
separates your application from the back end, while effectively
executing functions that are responsible for updating the screen almost
instantaneously as they occur.
What you choose to use as a communication bridge between the back
end and the front end is entirely up to you. React doesn't care about it.
Its purpose is strictly limited to updating the view as fast as possible.
This mounting mechanism make React a versatile library. Because at
its basic principle, React also doesn't care whether the final result is
rendered in the DOM or elsewhere.
You can render React output into an XML document, treat it as custom
object data, or return a JSON. It combines familiar programming
principles and tries to be "everything for everyone." This is what makes
React an incredibly powerful tool for programming User Interfaces as
well as fiddling around with custom software implementations.
Now, chances are that if you're coming to React from traditional pre-
2015 JavaScript background… unlike studying jQuery, learning React is
a much more involved process. It pertains to learning software
development principles rather than learning a set of method names and
you're ready to go!
However, it does have a few methods that are becoming standardized
among React programmers. We'll explore them as we move forward.
Simply knowing them, without understanding the fundamental
philosophy behind React is just not enough.
Gem 7 - Node.js & NPM
When I said that studying React involves learning much more than just
React library, it was certainly true. At the very least, working with
React requires that you install the Node library.
A whole another book can be written just about Node alone, but with
regard to React library, we need to install it for several reasons:
1. To provide a localhost environment for our React application.
Installing Node gives you the ability to run your applications from
http://localhost on your local machine.
2. Node automatically comes with Babel and JSX support (JSX is
installed as a Babel plugin.)
Installing Node and NPM is surprisingly easy on both Mac (via the
terminal) and the PC. On the PC it's as easy as downloading the Node
installation file from their official website. Run the installation program
and you're all set. Just don't forget to check the babel checkbox during
installation, so it's also included.
On a Mac, you can download Node via command line. Pop open your
Terminal application and type:
$ wget http://nodejs.org/dist/node-v0.4.4.tar.gz
$ tar -xzf node-v0.4.4.tar.gz
$ cd node-v0.4.4
$ ./configure
$ sudo make install
That's it! The configuration log will run and then you're done.
On Ubuntu, you might want to run this additional command to install
essential components:
$ apt-get -y install build-essential
It looks like at this point node is installed and ready to be utilized for
giving us a localhost http address where we can test our React code.
However, the good news is that if you already have Apache server
installed on your localhost machine, and it's mapped to your
development folder, using node for providing localhost environment is
not necessary. You already have it set up.
In this case, you can just start writing React programs right inside your
existing Apache httpdoc folder, or whatever folder it is mapped to on
your machine. Just create a new folder in that directory for example
"my-react-app", and as usual your project will be available for access
via browser under something like:
http://localhost/my-react-app
However, it is highly recommended that you do install Node. If for any
reason, it's because it comes with command line version of Babel and
JSX plugins, which will be required for proper development
environment set up.
The installation is really straightforward on a Mac in terminal. But on
PC it is just a bit more challenging, especially if you've never done this
before.
If you are still unsure on how to do any of this on a PC I recorded a 58-
minute supplementary tutorial on YouTube, available for free at the
following location:
React JS Tutorial 1 - For Beginners | ReactJS JavaScript ES6
Node.js, NPM, Babel Transpiler, Webpack
https://www.youtube.com/watch?v=tXaNvGcjEi0
It's worth going through regardless of where you are in the development
process. But it's a must-watch if you're just starting out.
Watching this tutorial should get you started with writing React
applications on a PC via the localhost address. So in that video tutorial
I walk you through the entire process, step by step. I don't want to
rewrite the details in this book to take any more space. You can watch it
at 2x speed and get through it in just about 25 minutes.
Gem 8 - JSX Walkthrough
If you've started studying React already, you should have heard a lot
about JSX. You've also probably heard that it is not necessary to use it
with React. And that much is true. But, it is recommended that you do. It
just makes things so much easier, even though its syntax can appear a
little scary at first to traditional JavaScript developers.
JSX is known for being a language that lets you "write HTML inside
JavaScript." This is true to some degree. The desired effect is that we
can treat HTML tags as a JavaScript statement. However, JSX actually
uses a form of XML which only resembles HTML, because it uses tag
names that match those of standard HTML tags, such as DIV, UL,
TABLE and so on. Remember that even HTML is just a distant brother
of XML.
Although HTML as a JavaScript statement might look a bit dinosauric at
first, once you grasp the idea and get used to it, it really becomes
second nature. It's definitely something completely new and not usually
done (and not even compile in most browsers today) but let's take a
look at what it actually looks like:
var scoreBoard = { Player1: 10, Player2: 25 };
<div className = "class1" />;
<SomeCounter count = { 3 + 5 } />
<ScoreBoardUnit data-index = "2">
<h1>Score Leaderboard</h1>
<Scoreboard className = "results" scores = {scoreBoard} />
</ScoreBoardUnit>;
This code naturally will not compile in your standard browser unless
Babel's JSX plugin is helping us transpile it back into ES5, the
specification we can be sure all modern browsers do understand. In
which case, it will compile into following React elements.
var scoreBoard = { Player1: 10, Player2: 25 };
React.createElement( 'div', { className: 'class1' }, null)
React.createElement( SomeCounter, { count: 3 + 5 }, null)
React.createElement( ScoreBoardUnit, { 'data-index': 2 },
React.createElement( 'h1', {}, 'Score Leaderboard'),
React.createElement( Scoreboard, {
className: 'result',
Scores: scoreBoard }, null)
) // close React.createElement( ScoreBoardUnit...
React.createClass({render: function() {
return (
<div>Hello World.</div>
)
}
});
var cn = document.getElementById("my_id").style.className;
This is standard JavaScript code. But JSX uses its own virtual DOM
system which tries to closely imitate it. It's not trying to reinvent the
wheel and create its own original processing language. And so
properties follow the standard format we're already familiar with from
working with DOM API object in JavaScript.
But there are a few other quirks. For example, you cannot use the
"className" keyword as HTML attribute name. Let's consider the
following example which creates a root component, consisting of just
one UL element, and calling it's class "my-list" by assigning it with
className property.
This is often mistaken for a JSX problem, thinking that JSX prohibits
the use of JavaScript reserved keywords. While this is a somewhat true
assessment, the problem stems from JSON notation, not JSX. The
common solution for this problem is to use quotes around property
name:
ReactDOM.render(
<H1>Hello</H1>,
document.getElementById('root')
);
Notice that we are typing HTML tags <H1> right into render's method
as an argument without surrounding quotes. This is syntactic style
offered by JSX. It normally will not compile in JavaScript, but
intelligent IDE's like PHPStorm are aware of JSX syntaxing and will
not treat it as an error.
As long as you have JSX included in your project (usually via babel .js
library or its counterpart command-line plugin, the latter being the one I
recommend using on your production server) this will compile just fine.
Now that we know that this will work only as long as you have babel
transpiler (babel.min.js) included in your project. (In order words, don't
attempt writing this in Notepad in some folder on your "Desktop" your
development environment must be properly set up in order for this to
compile, or at the very least babel.js should be included in SCRIPT tag
on your page.) It uses internal JSX processor to convert this inline
HTML into JavaScript.
Function Purity
Before we go into React props, I just wanted to mention one thing. In
React props are read-only. And this has a lot to do with a particular
type of a function called pure function. In traditional software
development a pure function is one which does not internally change its
arguments which are passed to it.
For example,
In React, props take on the "pure" ideology. This means you can pass
them, under the condition that your react component will not be
changing their values from within itself. This is exactly what makes
react props read-only. It's good to stick to that rule.
Props are derived from HTML element properties. It's a bit odd, that
they are called props. Because in HTML elements, properties are
single-keyword flags like DISABLED or CHECKED.
The better name for props would be attributes. Because they resemble
the name=value pair of HTML attributes not props. But, that's just the
way it is. React.js developers have chosen this naming convention!
Don't shoot the messenger:)
If you've been following our discussion from the previous chapter you
should now know what components are. They are combinations of
HTML, CSS and JavaScript code blocks that determine functionality of
one visual area of your application. They are responsible for updating
things like feed messages, alerts and various state updates.
We also know that a component usually has a render method to display
it in your app.
Working with React.js the next thing you will run into are props. Props
are like function arguments. Except you pass them to your component,
not functions. The principle is the same, however.
Let's create a component and pass a prop to it.
Functional Components
Above we have demonstrated a standard React component. It has all of
the complexities of one: it's created using createClass function, and
contains a render method. But the following code is actually also
considered a valid React component, even though it's nothing more than
a standard JavaScript function:
function Hello(props) {
return <H1>Hello, { props.name }</H1>;
}
What makes it a valid React component is the fact that it returns a React
element. React elements can be rendered on the screen. A lot of your
reactive code will be returning such statements. It's just a way of
bundling HTML elements and returning them as if it was a regular
JavaScript value.
This is a big part of React-style programming and it's easy to get used to
once you've actually programmed a few of them yourself. At first it will
feel awkward, but once you get used to it you'll really see the versatility
of this style of programming.
Remember that in JavaScript everything is an object, even functions.
This is why components like this are called functional components. In
a way, it's really just a different way of thinking about JavaScript
functions.
Note that we're using ES6 class keyword. We also use the new keyword
extend to derive this object from the standard React.Component which
is the default component object supplied by React library itself.
A Wolf in Sheep's Clothing
If you know how class inheritance works, well this is how it is imitated
in JavaScript. I say imitated, because under the veil, JavaScript still
uses prototype-based inheritance. Which can be a blessing and a
curse.
Inheritance standards defined by JavaScript are not really real,
compared to more mature languages such as C++ or Java. In other
words, you can forget creating advanced object structures such as
"interfaces" in JavaScript with its loose typing.
Strict programming languages are usually better at providing a fully
functional Object-Oriented Programming environment. And here,
EcmaScript developers decided to dress up JavaScript syntax a bit to
make the wolf look a little more like a sheep.
But most programmers agree that this syntax improves programming in
JavaScript. At least visually.
One other major difference of making components this way is access of
props.name property via this keyword variable. Otherwise it does
exactly what the functional component from previous example does.
Native Babel vs JavaScript Babel
I tried to subtly mention this in a previous chapter. But this deserves a
brief explanation before we move forward. I don't want you to
deceptively see babel at work, without knowing that it might not be
properly set up for real-world production environment.
It's best to run babel as a stand alone application in the background, as
part of your development environment. This comes with Node
installation by default. Simply download Node from Google and keep
clicking "Next" button to finish installation.
Adding babel directly via SCRIPT tag is possible and works for testing
things out. But because babel's JavaScript library is slower, it is
advised to install the native version that works from command line.
JavaScript babel library is just slow at processing something like this
and defies React programming, one of the sole purposes of which is to
optimize your app for speed.
NPM
Command line babel application comes together with Node.js
installation. So if you install Node, you will automatically have babel
packages. You just need to install them separately from command line
using NPM tool, which also comes with Node by default.
While learning React.js, it's perfectly normal to simply add babel via
SCRIPT tag. It's just not fast enough for production environment when
your app goes live. In any case, all babel does is "transpile" your
EcmaScript6 and JSX code back into EcmaScript5, so you can run it in
any browser that doesn't have full support for ES6 yet. (None of them
do, as of this writing.)
Transpiling Source Code
Eventually, when ES6 support is rolled out for all browsers it will be
safe to simply discontinue using babel for the purpose of transpiling
between EcmaScript specs. The code will work out of the box by
simply writing it within your standard JavaScript files.
But until then, we might as well use this opportunity to learn about a fun
source code tool. There are always new standards coming out, and the
art of transpiling is probably not going away anytime soon.
* * *
Where we have a callback function return upon the event has finished
executing. In react, we're returning an HTML element that will usually
be placed inside our application's structure on the front end.
In case of React components, it's just a JavaScript object that contains
render function, and has a return statement that returns transpiled JSX
code. That's what converts <Something> tag into EcmaScript5 that
browsers can understand.
What gets to be in render function and in return statement depends on the
purpose of your application. In this example, for the sake of clarity, let's
call these objects Parent and Child respectively. An actual pair of
names if you were writing an application could be something like
Friend and FriendList. Or Customer and CustomerProperty.
Parent with a Single Child
Using this pattern, you can implement a basic view functionality.
First, let's create the least building block of the pattern - the child.
In this case the child is a basic component that returns a button element.
The button provides an onClick event that will be executed by the
method this.props.onClick.
Let's now create its counterpart Parent class, and use Child as the
object it will return. I highlighted Child to make sure it's easy to see
how the Child component is tied to Parent.
var Parent = React.createClass({
render: function() {
return (
<Child onClick = { this.handleChildClick } text = { this.state.childText } />
);
},
handleChildClick: function( event ) {
// In this method, you can access props
// that were passed to the Child, using this.state property
var child_text = this.state.childText;
Each component is in charge of rendering its own state but the method
getInitialState is always called before our render function. This has
similar functionality to an object constructor function. Here we set the
default values.
You can use this method interchangeably with the default constructor
method provided in EcmaScript 6:
The only other notable difference here is that we're using the this
keyword to attach state to the main object.
We've already spoken of mounting earlier in the book. If you still need
to brush up on the process, I recommend making sure you've gone over
Gem 6 - Component Mounting previously discussed.
It simply means that the virtual DOM has become associated with a
DOM node that will be actually updated on the screen. This method is
always called after executing render command from the component.
They are synonymous and can probably be used interchangeably. It
ensures and tells us that the element actually already exists within
virtual DOM. The render method has already been called on it!
Method 3 - componentWillUnmount
Notice, we're resetting the state here back to null. The component is
destroyed and we no longer need its data. This is the place where you
would clean up memory used by your component, if any. For example
uninitialize timers.
Here, I will build a simple search app that looks up results from an
array set. If the typed characters match anything on the list, they will be
filtered out and all other entries will be dismissed.
This app is a lot like the Google search auto-look up feature where
items drop down as you type your phrase into the query input box.
Below I'm listing the full source code.
Here, I am not going to include Cascading Style Sheet part of the app.
This can be taken care of separately. We want to focus strictly on the
React implementation.
The app is surprisingly compact in comparison to everything you'd have
to do using standard JavaScript code, provided what it actually does.
Let's create the list of potential search results by using object literal
format in JavaScript:
handleChange: function(e) {
// Commenting the following line out, will result in the text box not changing its
value, because in React input boxes cannot change independently of the value that was
assigned to it. In this case it's the this.state.searchString.
this.setState({searchString: e.target.value});
},
// Render this component
render: function() {
searchString = this.state.searchString.trim().toLowerCase();
If (searchString.length > 0) {
// We are searching. Filter the results.
libraries = libraries.filter(function(l){
return l.name.toLowerCase().match( searchString );
});
}
<ul>
{ libraries.map(function(l) {
return <li>{l.name} <a href = {l.url} > {l.url}</a></li>
}) }
</ul>
</div>;
}
});
Place this code into the main .js file of your application and run it. It
will result in basic drop down functionality. Typing partial animal
names will filter them out from the main list. Ideally, you would load
this list from a database or some other data storage mechanism.
I hope this provides enough ammunition to start writing your own React
application.
The rest of the book will deal with going over some of the most
important changes to JavaScript language that were applied in
EcmaScript 6.
When React was created, it started out when ES5 specification was in the
spotlight. It was still new and fresh in 2015 and even throughout 2016.
When you are learning React, you are learning a lot more than just React. It
works in ES5 just fine, but that syntax is becoming outdated. And this is where
many programmers can get puzzled, because essentially the same library might
not look the same in all the different examples you're seeing on the Internet and
in books.
If you don't know React, chances are you probably don't know much about
EcmaScript 6 at all. I know this is a dangerous assumption to make, but I think
it can be justified by things you will learn in this chapter.
There really isn't anything wrong with ES5. But it isn't going away anytime
soon. And I think when writing educational books at a time when the industry
is still transitioning from one specification into another it's important to
occasionally juggle between the two.
But we've come to a place of the book where we will now investigate the
primary differences and additions to JavaScript in EcmaScript 6 specification.
At the end of the book I will also provide cheat sheets for many of the subjects
discussed here.
The var and let keywords
In ES6 it's commonly agreed that instead of using var keyword we now use let
keyword. There are reasons for this, which are described below:
{
console.log( a ); // undefined; but only because it is hoisted
var a = 1;
}
{
console.log( a ); // ReferenceError: "a" is not defined at all
let a = 1;
}
In the example above the result coming out of console when making an
attempt to print out value of a variable is undefined. In first case, it's because
while the variable is hoisted. But in the second example, because it is not.
❖ In global scope. The let keyword and the old var keyword are still
scoped to the global scope. But the let keyword is not attached to the
global window object:
function helloThere() {
let x = 1;// identical scoping
var y = 1; // identical scoping
}
Perhaps this is not the best example of var keyword (because the for loop is
where it's initially defined) because while it is available everywhere in the
function. But it still demonstrates the principle.
While this looseness is helpful in many cases and makes the learning curve
almost non existent, in the long run you will bump into these weird cases,
especially when your program reaches certain length in large projects.
So now, let's take a look at the same example. The only thing we did was swap
the var over with let keyword. This produces different scoping expectations.
// let example
function helloThereIterator() {
// i is not visible here
for (let i = 0; i < 10; i++) {
// i is visible here, and in callbacks within this scope itself
}
}
The var keyword (in strict mode) will let you redeclare its own value in
the same scope. But this is not true with let keyword:
'use strict';
var a = 1; // Ok.
var a = 2; // Ok. a is now 2;
'use strict';
let a = 1; // Ok.
let a = 2; // Syntax error: identifier a is already declared.
❖ The let keyword can also be used to avoid problems with closures. It
will bind a new value instead of keeping a reference to the old one.
"use strict";
for (let i = 1; i < 10; i++) {
$.ajax("url": "script.php", function(msg) {
console.log(i); // the variable i has lost its original scope here, it's no
longer associated with the i variable defined in the for loop
} );
}
However, this is not true when let is used to defined the same loop. It
effectively resolves this common problem. Here is the same example,
only this time using let.
"use strict";
for (var i = 1; i < 10; i++) {
$.ajax("url": "script.php", function(msg) {
console.log(i); // here i is the one that was originally defined in for loop
} );
}
This definitely saves many headaches associated with for loops and
callback functions.
{
let a = 1;
};
Whereas the let keyword is only known by the scope block in which it is
defined and all other scopes within it even if it's a callback function.
This doesn't solve any major software problems but it certainly helps us
get things done in a more intuitive way, especially when dealing with the
web of multiple scopes in our script's program structure.
The new const keyword
Const is exactly like let. The only difference is that once you define a value
using const it cannot be redefined again later on in your program. Doing this
will produce an error:
let a = 1;
a = 2; // this is ok, we simply reassigned the value of a variable
const a = 1;
a = 2; // error, this is a constant and cannot be reassigned!
How is this useful? Constant variables are traditionally used in computer
programs to define values that will not change at runtime throughout your
application. They are great for flag values and app configuration settings that
should not change.
Oh, and one more thing… When it comes to objects only… const keyword,
while prevents re-assignment does not actually make the assigned object
immutable. In contrast to many other languages, making an object const would
make its properties immutable as well.
Not so in JavaScript.
Destructuring assignment
let a = obj.a;
let b = obj.b;
This format takes a lot more space. Destructuring assignments save space and
provide better readability for our code. Get used to them! :)
For-of loop
This mighty for loop will iterate through values stored in map. Unfortunately
(like many things in JavaScript) the for-of loops do not work on objects (and
their properties). This is almost a bewildering design decision. So, what do
for-of loops can work on?
The for-of loops are designed exclusively to work with Array, Map and Set
objects only.
The Map object
Just like an Array object, ES6 adds a new one, called Map. Maps are nothing
more than a simple key/value map. They are a lot like associative arrays in
PHP.
Maps should not be used everywhere. Only where you previously used objects
as collections. That's what they're made for. And using objects should still be
primary to your JavaScript program design.
Maps have a .size property which determines its size. Unlike objects, where
you would have to calculate the size of an object manually. Use them together
with for-of loops when you have collections of data paired by key/value
association!
Arrow Functions
One of the most favored features in EcmaScript6 is the arrow functions. I think
you should start using them at earliest opportunity. Arrow functions are just
JavaScript functions written in a more compact syntax and that are slightly
different than regular functions created using the function keyword. Here is the
basic arrow function syntax format, which at first may seem a little odd:
For example, you can write something like this using an arrow function:
But this is only a function definition. It can be executed just like a regular
function as follows:
x(5, 7);
Arrow functions also modifies the functionality of the this object used within
nameless callback functions within object scope definition by automatically
binding it to topmost local scope of the object. It reminds me a little of hoisting
(I briefly talk about hoisting in my other tutorial).
Arrow functions help us escape this/that gymnastics (If you're not familiar
with what I'm referring to keep on reading, this tutorial explains it) inherent to
original scope model we've been used to.
Arrow functions are also known as "fat arrow" functions due to their syntax.
The rest of this tutorial will explain the difference between an older JavaScript
example and how arrow functions can be used to improve code readability and
internally tweak object functionality.
The aim of arrow functions is to solve a fundamental problem that stems from
original JavaScript language design dealing with object scoping and the
automatic this keyword binding.
Let's consider we have this simplified version of an object called Sprite for
making game character and enemy object sprites!
Also let's create a new "ship" object of type Sprite and instantiate it.
Notice the draw function. In this simple example we output the current angle of
rotation for our sprite. In real world circumstance the code would be actually
more complicated. But this is just an example to demonstrate arrow functions
in JavaScript.
Shall we take a look now? I am building on top of the code we already saw in
the previous example. So I am repeating it here. But there is a new addition. I
added setTimeout function, which takes an anonymous function and executes it
in 1 second (1000 milliseconds) after Sprite object is instantiated. This is
normal behavior of a JavaScript function-object constructor.
Undefined
All I did in this example was assign this object to the newly created that
variable within main Sprite object's scope. Before timer was defined. So in
reality we now have something like this.that within Sprite.
Let's run our code this time and see what happens now:
I am sure you have used the trick I just described in the examples above
before. If not, well I'm glad you know about it now. Most programmers
discover it by instinct. Because it takes time to learn the difference in
JavaScript scoping rules between function objects and anonymous events
within those functions.
And after all these explanations with a big smile on our face this finally brings
us to our big final question!
What are Arrow Functions in JavaScript?
And what is the difference between an arrow function and anonymous functions
in JavaScript?
Notice that both do exactly the same thing, execute some code. Except arrow
functions automatically take care of the cumbersome this/that juggling we
have just experienced in the previous examples. Arrow functions create their
own local this object that doesn't change. So we never have to rename or bind
it to another variable such as that, like in previous example.
This is the new syntax in EcmaScript 6 that defines new arrow function in
JavaScript:
() => { };
Note that params can include a set of multiple parameters separated by comma.
In which case you must always use parenthesis. For single parameter syntax,
you don't have to use parenthesis.
In a real world-scenario we can also assign arrow functions to a variable
name. In this case the anonymous arrow function becomes named. The function
returns the result from within its body's scope.
But there is another, scope-less variation syntax for defining arrow functions:
And finally let's put it all together and rewrite our original example of the
Sprite object. Only now using an arrow function. You can see that there is no
necessity to create and set binding of this to that variable anymore. Arrow
functions take care of that for you, for us!
From that moment on this keyword within the new anonymous event function
started to correctly refer to this keyword from the original Sprite object.
Without us having to write any extra binding code.
And so... I think this concludes our discussion of arrow functions. I hope you
enjoyed this tutorial. Please share it with your friends, on Twitter or on your
Facebook page.
Developer Post is a small website dedicated to simple explanations of
subjects that otherwise appear complex. And hopefully this helps someone out
there write better JavaScript code.
If you want to learn more about ES6 Harmony, head to What's new in
EcmaScript 6 aka Harmony (opens new tab) to get familiar with the basics.
According to this Sitepoint article, arrow functions are the most favorite
feature in ES6.
This Mozilla arrow function tutorial helped me become familiar with arrow
functions. I used it as my first reference while writing this article.
Immediately Invoked Arrow Functions (IIAF)
You will find this syntax used often at the bottom of the HTML page just above
the closing body tag. This technique is used to wait until the HTML elements
have finished loading until starting to execute JavaScript.
In the same way, arrow functions can be used to achieve equivalent result.
Backtick is just another name for the quirky quote character, also known as
grave accent.
One of the best things about backticked strings is that they can be split over
multiple lines. A much needed feature that was lacking in JavaScript.
These types of strings are also called template literals. Below several
examples are shown:
`string text`;
`string text on line one
Can continues here without semicolons`;
You can also use both regular single quote (') and double quote (") characters
within grave accents.
New Array methods
The following are the most important additions to the Array objects in ES6.
find
arr.find(callback[, thisArg]);
Returns the value of the first item which, when passed to callback, produces a
"truthy" value.
findIndex
arr.findIndex(callback[, thisArg]);
The findIndex method is exactly the same as find. The difference is that it will
return the index of the first item which produces a "truthy" value, not the value.
fill
The fill method initializes or "fills" all of the elements at every index of an
array. It can initialize or set only a sector of your array by taking optional
parameters start and end:
This new array method copies a sequence of items within itself as an array,
starting at the position indicated by start and starting from index indicated by
target:
This code, apparently copies the "1,1,1" sequence, starting at 0 index in the
array and copies it over to the last 3 indices, that start at target index of 6.
This is a lot like memory operations in C++, except with arrays.
Built in classes are the pre-existing objects that come packaged with
JavaScript. For example the familiar ones are Object, Array, Function, Date,
Math and a few others… EcmaScript 6 adds several new built in classes
which are listed below:
Promises are interesting because all events usually take place at a future time
anyway. What's so different about a promise? The proper explanation would
be to say that they will take place regardless of whether the structure of your
HTML document changes. These special events, called "promises" guarantee
that the event will take place at some time in the future.
One of the problems promises solve is the classic case when HTML element's
events (such as onclick) are overwritten by code that updates visual aspects of
your application. Because this happens often in an actively updated front-end
view, some events might not be triggered at all, just because DOM was
rewritten.
A promise can exist "in the future" regardless of what happens to DOM
structure of your site, so long as the integrity of the original DOM remains the
same, or similar to one that existed at the moment when the event was
executed.
Thank You
This tutorial book was independently published by me and distributed
to subscribers of my free JavaScript newsletter. This couldn't have been
a possibility without your support.
Have you ever tried writing and pushing your own books? Hours of
research and mental processing goes into crafting a technical book!
This is why, I wanted to dedicate this section to just saying thank you
for buying a copy of React Gems. As you may know, your purchase
includes free life-time book updates.
Free updates are already included with your purchase and you don't
have to do anything to continue receiving them.
Author,
Greg Sidelnikov
greg.sidelnikov@gmail.com