React 2
React 2
Over the next 30 days, you'll get a good feel for the various parts of the React
(https://facebook.github.io/react/) web framework and its ecosystem.
Each day in our 30 day adventure will build upon the previous day's materials,
so by the end of the series, you'll not only know the terms, concepts, and
underpinnings of how the framework works, but be able to use React in your
next web application.
What is React?
React (https://facebook.github.io/react/) is a JavaScript library for building
user interfaces. It is the view layer for web applications.
1
are composable. A component might include one or more other components
in its output.
For example, take a form. A form might consist of many interface elements,
like input fields, labels, or buttons. Each element inside the form can be
written as a React component. We'd then write a higher-level component,
the form component itself. The form component would specify the structure
of the form and include each of these interface elements inside of it.
For instance, the Hello world example of a React website can be as simple as:
2
Although it might look a little scary, the JavaScript code is a single line that
dynamically adds Hello world to the page. Note that we only needed to
include a handful of JavaScript files to get everything working.
3
The React Virtual DOM (https://facebook.github.io/react/docs/dom-
differences.html) exists entirely in-memory and is a representation of the
web browser's DOM. Because of this, when we write a React component,
we're not writing directly to the DOM, but we're writing a virtual component
that React will turn into the DOM.
In the next article, we'll look at what this means for us as we build our React
components and jump into JSX and writing our first real components.
4
What is JSX?
Edit this page on Github (https://github.com/fullstackreact/30-days-of-react/blob/master/day-02/post.md)
Now that we know what React is, let's take a look at a few terms
and concepts that will come up throughout the rest of the
series.
JSX/ES5/ES6 WTF??!
In any cursory search on the Internet looking for React material, no doubt
you have already run into the terms , ES5, and ES6. These opaque
acronyms can get confusing quickly.
ES5 (the stands for ECMAScript) is basically "regular JavaScript." The 5th
update to JavaScript, ES5 was finalized in 2009. It has been supported by all
major browsers for several years. Therefore, if you've written or seen any
JavaScript in the recent past, chances are it was ES5.
ES6 is a new version of JavaScript that adds some nice syntactical and
functional additions. It was finalized in 2015. ES6 is almost fully supported
(http://kangax.github.io/compat-table/es6/) by all major browsers. But it
5
will be some time until older versions of web browsers are phased out of use.
For instance, Internet Explorer 11 does not support ES6, but has about 12% of
the browser market share.
In order to reap the benefits of ES6 today, we have to do a few things to get it
to work in as many browsers as we can:
6
To see what this means, imagine we had a React component that renders an
HTML tag. JSX allows us to declare this element in a manner that closely
resembles HTML:
Hello World
The function in the component looks like it's returning
HTML, but this is actually JSX. The JSX is translated to regular JavaScript at
runtime. That component, after translation, looks like this:
While JSX looks like HTML, it is actually just a terser way to write a
declaration. When a component renders, it outputs a
tree of React elements or a virtual representation of the HTML elements this
component outputs. React will then determine what changes to make to the
actual DOM based on this React element representation. In the case of the
component, the HTML that React writes to the DOM will look
like this:
7
The syntax we used in our first React
component is ES6 syntax. It allows us to write objects using a
familiar Object-Oriented style. In ES5, the syntax
might be translated as:
8
Again, while you can skip JSX and write the latter directly, the JSX syntax is
well-suited for representing nested HTML elements.
Now that we understand JSX, we can start writing our first React
components. Join us tomorrow when we jump into our first React app.
9
Our First Components
Edit this page on Github (https://github.com/fullstackreact/30-days-of-react/blob/master/day-03/post.md)
Let's revisit the "Hello world" app we introduced on day one. Here it is again,
written slightly differently:
10
Hello world
Loading the React library
We've included the source of React as a tag inside the
element of our page. It's important to place our loading tags before
we start writing our React application otherwise the and
variables won't be defined in time for us to use them.
Babel
11
Yesterday, we talked about ES5 and ES6. We mentioned that support for ES6
is still spotty. In order to use ES6, it's best if we transpile our ES6 JavaScript
into ES5 JavaScript to support more browsers.
This signals to Babel that we would like it to handle the execution of the
JavaScript inside this body, this way we can write our React app using
ES6 JavaScript and be assured that Babel will live-transpile its execution in
browsers that only support ES5.
12
We've written a React application. Our "app" is a React element which
represents an tag. But this isn't very interesting. Rich web applications
accept user input, change their shape based on user interaction, and
communicate with web servers. Let's begin touching on this power by
building our first React component.
Let's look at a component we'll call . Like all other React components, this
ES6 class will extend the class from the React package:
In our , let's replace our JavaScript from before with our new
component.
13
However, nothing is going to render on the screen. Do you remember why?
The idea that our React components act just like any other element on our
page allows us to build a component tree just as if we were creating a native
browser tree.
While we're rendering a React component now, our app still lacks richness or
interactivity. Soon, we'll see how to make React components data-driven and
dynamic.
But first, in the next installment of this series, we'll explore how we can layer
components. Nested components are the foundation of a rich React web
application.
15
Complex Components
Edit this page on Github (https://github.com/fullstackreact/30-days-of-react/blob/master/day-04/post.md)
Awesome, we've built our first component. Now let's get a bit
fancier and start building a more complex interface.
In the previous section of 30 Days of React, we started building our first React
component. In this section, we'll continue our work with our component
and start building a more complex UI.
16
Styles
As we're not focusing on CSS
(https://www.w3.org/standards/webdesign/htmlcss) in this course,
we're not covering the CSS specific to build the timeline as you see it on
the screen.
However, we want to make sure the timeline you build looks similar to
ours. If you include the following CSS as a tag in your code, your
timeline will look similar and will be using the same styling ours is using:
And make sure to surround your code in a component with the class of
(we left it this way purposefully as it's the exact same code we use in
all the demos here). Check out the
https://jsfiddle.net/auser/zwomnfwk/
(https://jsfiddle.net/auser/zwomnfwk/) for a working example.
In addition, in order to make the timeline look exactly like the way ours
does on the site, you'll need to include font-awesome
(http://fontawesome.io/) in your web application. There are multiple
ways to handle this. The simplest way is to include the link styles:
17
All the code for the examples on the page is available at the github repo
(at https://github.com/fullstackreact/30-days-of-react)
(https://github.com/fullstackreact/30-days-of-react).
18
19
20
Timeline
An hour ago
Ate lunch
10 am
Read Day two article
10 am
Lorem Ipsum is simply dummy text of the printing and
typesetting industry.
2:21 pm
Lorem Ipsum has been the industry's standard dummy
text ever since the 1500s, when an unknown printer
took a galley of type and scrambled it to make a type
specimen book.
Breaking it down
Rather than build this in a single component, let's break it down into multiple
components.
21
We can chop up the content part of the component into individual places of
concern. There are 3 different item components inside the content part.
22
If we wanted to go one step further, we could even break
down the title bar into 3 component parts, the menu button,
the title, and the search icon. We could dive even further into
each one of those if we needed to.
In any case, it's usually a good idea to start looking at applications using the
idea of components. By breaking our app down into components it becomes
easier to test and easier to keep track of what functionality goes where.
None of these components will require special functionality (yet), so they will
look similar to our component in that it's just a component with
a single render function.
Let's build a wrapper component we'll call that might look similar to this:
23
Notice that we use the attribute called in React
instead of the HTML version of . Remember that we're
not writing to the DOM directly and thus not writing HTML,
but JSX (which is just JavaScript).
Child components
When a component is nested inside another component, it's called a child
component. A component can have multiple children components. The
component that uses a child component is then called it's parent component.
For instance, the header component looks like this, with a container element
, the menu icon, a title, and the search bar:
24
Timeline
And finally, we can write the component with timeline items. Each
timeline item is wrapped in a single component, has an avatar associated
with it, a timestamp, and some text.
25
26
In order to write a comment in a React component, we have
to place it in the brackets as a multi-line comment in
JavaScript.
27
Timeline
An hour ago
Doug 2
Ate lunch
Note!
With this knowledge, we now have the ability to write multiple components
and we can start to build more complex applications.
However, you may notice that this app does not have any user interaction nor
custom data. In fact, as it stands right now our React application isn't that
much easier to build than straight, no-frills HTML.
In the next section, we'll look how to make our component more dynamic
and become data-driven with React.
28
29
Data-Driven
Edit this page on Github (https://github.com/fullstackreact/30-days-of-react/blob/master/day-05/post.md)
Through this point, we've written our first components and set them up in a
child/parent relationship. However, we haven't yet tied any data to our React
components. Although it's a more pleasant experience (in our opinion)
writing a website in React, we haven't taken advantage of the power of React
to display any dynamic data.
Going data-driven
Recall, yesterday we built the beginning of our timeline component that
includes a header and an activity list:
Timeline
An hour ago
Ate lunch
10 am
30
Read Day two article
10 am
Lorem Ipsum is simply dummy text of the printing and
typesetting industry.
2:21 pm
Lorem Ipsum has been the industry's standard dummy
text ever since the 1500s, when an unknown printer
took a galley of type and scrambled it to make a type
specimen book.
We broke down our demo into components and ended up building three
separate components with static JSX templates. It's not very convenient to
have to update our component's template everytime we have a change in our
website's data.
Instead, let's give the components data to use to display. Let's start with the
component. As it stands right now, the component
only shows the title of the element as . It's a nice element and it
would be nice to be able to reuse it in other parts of our page, but the title of
doesn't make sense for every use.
Let's tell React that we want to be able to set the title to something else.
Introducing props
React allows us to send data to a component in the same syntax as HTML,
using attributes or properties on a component. This is akin to passing the
attribute to an image tag. We can think about the property of the
tag as a we're setting on a component called .
31
We can access these properties inside a component as . Let's see
in action.
32
We can pass in our as a prop as an attribute on the by
updating the usage of the component setting the attribute called to
some string, like so:
Timeline
33
We've also updated the code slightly to get closer to what our
final code will look like, including adding a
and a few elements to style the .
34
Results in four components to mount like so:
Timeline
Profile
Settings
Chat
Instead of statically setting the content and date let's take the
component and set the timeline content by a data variable instead of by text.
Just like we can do with HTML components, we can pass multiple into
a component.
36
Let's say that we have a JavaScript object that represents an activity item. We
will have a few fields, such as a string field (text) and a date object. We might
have some nested objects, like a and . For instance:
In order to pass a dynamic variable's value into a template, we have to use the
template syntax to render it in our template. For instance:
37
38
We've use a little bit of ES6 in our class definition on the first
line of the function called destructuring. The two
following lines are functionally equivalent:
We can then use this new content by passing in an object as a prop instead of
a hard-coded string. For instance:
1582840847478
Nate 1
Ate lunch
Fantastic, now we have our activity item driven by an object. However, you
might have noticed that we would have to implement this multiple times with
different comments. Instead, we could pass an array of objects into a
component.
39
Let's say we have an object that contains multiple activity items:
However, if we refresh the view nothing will show up! We need to first update
our component to accept multiple activities. As we learned about
previously, JSX is really just JavaScript executed by the browser. We can
execute JavaScript functions inside the JSX content as it will just get run by
the browser like the rest of our JavaScript.
Let's move our activity item JSX inside of the function of the function
that we'll run over for every item.
40
1582840847479
Nate 1
Ate lunch
1582840847479
41
Ari Woke up early for a beautiful run 1
Now we can pass any number of activities to our array and the
component will handle it, however if we leave the component right now, then
we'll have a relatively complex component handling both containing and
displaying a list of activities. Leaving it like this really isn't the React way.
ActivityItem
Here is where it makes sense to write one more component to contain
displaying a single activity item and then rather than building a complex
component, we can move the responsibility. This will also make it
easier to test, add functionality, etc.
42
Not only is this much simpler and easier to understand, but it makes testing
both components easier.
43
1582840847479
Nate 1
Ate lunch
1582840847479
Ari 1
Woke up early for a beautiful run
44
This week we updated our components to be driven by data by using the
React concept. In the next section, we'll dive into stateful components.
45
State
Edit this page on Github (https://github.com/fullstackreact/30-days-of-react/blob/master/day-06/post.md)
We've almost made it through the first week of getting up and running on
React. We have worked through JSX, building our first components, setting
up parent-child relationships, and driving our component properties with
React. We have one more major idea we have yet to discuss about React, the
idea of state.
The of things
React does not allow us to modify on our components for good
reason. Imagine if we passed in the prop to the component
and the component was able to modify it. How do we know what the
is of the component? We set ourselves up for race-conditions,
confusing data state, and it would be an all-around bad idea to modify a
variable passed to a child component by a parent component.
For instance, let's say we have a simple clock component that shows the
current time:
4:00:52 pm
Even though this is a simple clock component, it does retain state in that it
needs to know what the current time is to display. Without using , we
could set a timer and rerender the entire React component, but other
components on the page may not need rerendering... this would become a
headache and slow when we integrate it into a more complex application.
Instead, we can set a timer to call rerender inside the component and change
just the internal state of this component.
Let's take a stab at building this component. First, we'll create the component
we'll call .
Before we get into the state, let's build the component and create the
function. We'll need to take into account the number and prepend
a zero ( ) to the number if the numbers are smaller than 10 and set the
appropriately. The end result of the function might look
something like this:
47
Alternative padding technique
Alternatively, we could use the short snippet to handle padding the clock
time:
In order to do that, we'll need to track the current time in the state of the
component. To do this, we'll need to set an initial state value.
In the ES6 class style, we can set the initial state of the component in the
by setting to a value (the return value of our
function).
49
The first line of the constructor should always call
. If you forget this, the component won't like
you very much (i.e. there will be errors).
50
Instead of working directly with data values, we can now update the of
the component and separate the function from the data
management.
51
To start updating the timer immediately after the our
component has been rendered, we call in a
React component lifecycle method called
.We will get into the lifecycle hooks in the
next section.
In the function we'll want to update the state with the new
time. We can now update the state in the function:
52
The component will be mounted on the page and will update the time every
second (approximately every 1000 milliseconds)
Now the component itself might rerender slower than the timeout function
gets called again, which would cause a rerendering bottleneck and needlessly
using up precious battery on mobile devices. Instead of calling the
function after we call , we can pass a second
argument to the function which will be guaranteed to be
called after the state has been updated.
53
54
Styles
As we're not focusing on CSS
(https://www.w3.org/standards/webdesign/htmlcss) in this course,
we're not covering the CSS specific to build the clock as you see it on the
screen.
However, we want to make sure the clock you build looks similar to ours.
If you include the following CSS as a tag in your code, your
clock will look similar and will be using the same styling ours is using:
4:00:52 pm
55
bad idea to store objects or calculations in the state that we don't plan
on using in the function as it can cause unnecessary rendering
and wasteful CPU cycles.
Today, we've updated our components to be stateful and now have a handle
on how to make a component stateful when necessary. Tomorrow we'll dive
into the lifecycle of a component and when/how to interact with the page.
56
Lifecycle Hooks
Edit this page on Github (https://github.com/fullstackreact/30-days-of-react/blob/master/day-07/post.md)
Today, we'll look through a few of the most common lifecycle hooks we can
use with React components and we'll discuss why they are useful and when
we should each one.
Congrats! We've made it to the end of the first week on React and we've
already covered so much ground. We just finished working with stateful
components to keep track of a component's internal state. Today, we're going
to pause on implementation and talk a bit about how a component lives in an
application. That is, we'll talk about the component's lifecycle.
As React mounts our application, it gives us some hooks where we can insert
our own functionality at different times in the component's lifecycle. In order
to hook into the lifecycle, we'll need to define functions on our component
which React calls at the appropriate time for each hook. Let's dive into the
first lifecycle hook:
/
57
When a component is defined on a page in our application, we can't depend
upon it being available in the DOM immediately as we're defining virtual
nodes. Instead, we have to wait until the component itself has actually
mounted in the browser. For functionality that we need to run when it has
been mounted, we get two different hooks (or functions) we can define. One
that is called just before the component is due to be mounted on the page
and one that is called just after the component has been mounted.
This is useful for things such as fetching data to populate the component. For
instance, let's say that we want to use our activity tracker to display github
events, for example. We will want to load these events only when the data
itself is going to be rendered.
58
Let's update the component to make a request to the github.com
events api (https://developer.github.com/v3/activity/events/) and use the
response to display the activities. As such, we'll need to update the of
the object.
Timeline
An hour ago
Ate lunch
10 am
Read Day two article
10 am
Lorem Ipsum is simply dummy text of the printing and
typesetting industry.
2:21 pm
Lorem Ipsum has been the industry's standard dummy
text ever since the 1500s, when an unknown printer
took a galley of type and scrambled it to make a type
specimen book.
59
As we did yesterday, let's update our component to be stateful by setting
to an object in the constructor
Now, we'll want to make an HTTP request when the component itself is
getting ready to be mounted (or just after it mounts). By defining the function
(or ) in our component, React
runs the method just before it mounts in the DOM. This is a perfect spot for
us to add a request.
Let's update the component with the request to the github api.
Since we'll only want to display a small list, let's take the latest four events.
60
We've stored a static JSON file of github data that we'll load
directly from source here (we'll get back to making AJAX
requests in a few days) using promises. For now, let's focus on
how we'll implement updating our component with new data:
61
Notice that we didn't change anything else from our component and
it just works.
3 years ago
fullstackreact/react-yelp-clone
vigosan started
3 years ago
fullstackreact/react-native- restack
caveman started
3 years ago
fullstackreact/react-native- restack
jamesryancooper started
3 years ago
fullstackreact/react-native-oauth
element6 started 62
/
Sometimes we'll want to update some data of our component before or after
we change the actual rendering. For instance, let's say we want to call a
function to set up the rendering or call a function set when a component's
props are changed. The method is a reasonable hook
to handle preparing our component for a change (as long as we don't call
to handle it as it will cause an infinite loop).
Since we won't really need to handle this in-depth, we won't worry about
setting up an example here, but it's good to know it exists. A more common
lifecycle hook we'll use is the hook.
React will call a method when the component is about to receive new .
This is the first method that will be called when a component is going to
receive a new set of props. Defining this method is a good time to look for
updates to specific as it gives us an opportunity to calculate changes
and update our component's internal state.
This is the time when we can update our state based on new props.
63
One thing to keep in mind here is that even though the
method gets called, the value of
the may not have changed. It's always a good idea to
check for changes in the prop values.
For instance, let's add a refresh button to our activity list so our users can
request a rerequest of the github events api.
64
65
Notice that we have a new element here that displays the children of the
element. This is a pattern which allows us to add a CSS class around some
content.
66
Let's also update our method to call
instead of
67
Timeline
3 years ago
fullstackreact/react-yelp-clone
vigosan started
3 years ago
fullstackreact/react-native- restack
jamesryancooper started
3 years ago
fullstackreact/react-native-oauth
element6 started
3 years ago
fullstackreact/react-native- restack
caveman started
Refresh
This demo is using static data from a JSON file and randomly
picking four elements when we refresh. This is set up to
simulate a refresh.
For instance, with our clock component we worked on last time, we set a
timeout to be called every second. When the component is ready to
unmount, we want to make sure we clear this timeout so our JavaScript
doesn't continue running a timeout for components that don't actually exist.
69
When our clock is going to be unmounted, we'll want to clear the timeout we
create in the function on the component. Adding the
function takes care of this necessary cleanup.
4:00:55 pm
These are a few of the lifecycle hooks we can interact with in the React
framework. We'll be using these a lot as we build our react apps, so it's a good
idea to be familiar with them, that they exist, and how to hook into the life of
a component.
We did introduce one new concept in this post which we glossed over: we
added a callback on a component to be called from the child to it's parent
component. In the next section, we're going to look at how to define and
document the API of a component for usage when sharing a component
across teams and an application in general.
70
71
Packaging and PropTypes
Edit this page on Github (https://github.com/fullstackreact/30-days-of-react/blob/master/day-08/post.md)
In this section, we're going to look a bit at annotating and packaging our
components.
PropTypes
You may have noticed we use quite a bit in our components. For the
most part, we'll expect these to be a particular type or set of types (aka an
or a ). React provides a method for defining and validating
these types that allow us to easily expose a component API.
Not only is this a good practice for documentation purposes, it's great for
building reusable react components (https://reactjs.org/docs/components-
and-props.html).
72
From within this , we can define an object which has the key of a prop
as the name of the prop we are defining and a value defines the type (or
types) it should be defined as.
For instance, the component we built a few days ago accepts a a prop
called and we expect it to be a string. We can define it's type to be a
string as such:
You can also use the object directly in your browser by adding
the following tag in your page
73
React has a lot of types to choose from, exported on the object
and even allows for us to define a custom object type. Let's look at an overall
list of available types:
Basic types
React exposes a few basic types we can use out of the box.
Function
Symbol Symbol("msg")
Object
Anything 'whatever', 10,
It's possible to tell React we want it to pass through anything that can be
rendered by using :
74
We've already looked at how to communicate from a parent component to a
child component using . We can communicate from a child component
to a parent component using a function. We'll use this pattern quite often
when we want to manipulate a parent component from a child.
Collection types
We can pass through iterable collections in our . We've already seen
how we can do this when we passed through an array with our activities. To
declare a component's proptype as an array, we can use the
annotation.
We can also require that an array holds only objects of a certain type using
.
It's possible to describe an object that can be one of a few different types as
well using .
75
Object types
It's possible to define types that need to be of a certain shape or instance of a
certain class.
React types
76
We can also pass through React elements from a parent to a child. This is
incredibly useful for building templates and providing customization with the
templates.
When we use element, React expects that we'll be able to accept a single child
component. That is, we won't be able to pass multiple elements.
Requiring types
It's possible to require a prop to be passed to a component by appending any
of the proptype descriptions with :
77
Setting a as required is very useful for times when the component is
dependent upon a to be passed in by it's parent component and won't
work without it.
Custom types
Finally, it's also possible to pass a function to define custom types. We can do
this for a single prop or to validate arrays. The one requirement for the
custom function is that if the validation does not pass, it expects we'll return
an object:
Custom 'something_crazy'
['something',
CustomArray
'crazy']
Default props
Sometimes we want to be able to set a default value for a prop. For instance,
our component, we built yesterday might not require a title to be
passed. If it's not, we'll still want a title to be rendered, so we can define a
common title instead by setting it's default prop value.
To set a default prop value, we can use the object key on the
component.
78
Phew, today we went through a lot of documentation. It's always a good idea
to build our resuable components using the and
attributes of components. Not only will it make it easier to communicate
across developers, it'll be much easier when we return to our components
after leaving them for a few days.
Next, we'll get back to code and start integrating some style into our
components.
79
Styles
Edit this page on Github (https://github.com/fullstackreact/30-days-of-react/blob/master/day-09/post.md)
Today, we'll spend time working through a few ways how to style our React
components to make them look great, yet still keeping our sanity. We'll even
work through making working with CSS a bit easier too!
CSS
Using CSS to style our web applications is a practice we're already familiar
with and is nothing new. If you've ever written a web application before, you
most likely have used/written CSS. In short, CSS is a way for us to add style
to a DOM component outside of the actual markup itself.
80
Using CSS alongside React isn't novel. We'll use CSS in React just like we use
CSS when not using React. We'll assign ids/classes to components and use
CSS selectors to target those elements on the page and let the browser
handle the styling.
Orange header
Let's say we wanted to turn the header color orange using CSS. We can easily
handle this by adding a stylesheet to our page and targeting the CSS class of
in a CSS class.
81
We can target the by defining the styles for a class in a
regular css file. As per-usual, we'll need to make sure we use a tag
to include the CSS class in our HTML page. Supposing we define our styles in
a file called in the same directory as the file, this
tag will look like the following:
82
Orange header
One of the most common complaints about CSS in the first place is the
cascading feature itself. The way CSS works is that it cascades (hence the
name) parent styles to it's children. This is often a cause for bugs as classes
often have common names and it's easy to overwrite class styles for non-
specific classes.
Using our example, the class name of isn't very specific. Not only
could the page itself have a header, but content boxes on the page might,
articles, even ads we place on the page might have a class name of .
83
One way we can avoid this problem is to use something like
css modules (https://glenmaddern.com/articles/css-
modules) to define custom, very unique CSS class names for
us. There is nothing magical about CSS modules other than it
forces our build-tool to define custom CSS class names for us
so we can work with less unique names. We'll look into using
CSS modules a bit later in our workflow.
Inline styles
Adding styles to our actual components not only allow us to define the styles
inside our components, but allow us to dynamically define styles based upon
different states of the app.
React gives us a way to define styles using a JavaScript object rather than a
separate CSS file. Let's take our component one more time and
instead of using css classes to define the style, let's move it to inline styles.
Defining styles inside a component is easy using the prop. All DOM
elements inside React accept a property, which is expected to be an
object with camel-cased keys defining a style name and values which map to
their value.
84
This text will have the color blue
In any case, as these are JS-defined styles, so we can't use just any ole' css
style name (as would be invalid in JavaScript). Instead,
React requires us to camel-case the style name.
camelCase (https://en.wikipedia.org/wiki/CamelCase) is
writing compound words using a capital letter for every word
with a capital letter except for the first word, like
and .
85
To update our header component to use these styles instead of depending on
a CSS class definition, we can add the prop along with a
prop:
86
Our header will be orange again.
87
Orange header
Styling libraries
The React community is a pretty vibrant place (which is one of the reasons it
is a fantastic library to work with). There are a lot of styling libraries we can
use to help us build our styles, such as Radium
(https://formidable.com/open-source/radium/) by Formidable labs.
We won't dive into Radium in this post as it's more outside the scope of this
series, but knowing other libraries are good to be aware of, especially if
you're looking to extend the definitions of your inline styles.
Now that we know how to style our components, we can make some good
looking ones without too much trouble. In the next section, we'll get right
back to adding user interactivity to our components.
88
Interactivity
Edit this page on Github (https://github.com/fullstackreact/30-days-of-react/blob/master/day-10/post.md)
Through this point, we've built our few handful of components without
adding much user interaction. Today, we're going to change that.
User interaction
The browser is an event-driven application. Everything that a user does in
the browser fires an event, from clicking buttons to even just moving the
mouse. In plain JavaScript, we can listen for these events and attach a
JavaScript function to interact with them.
89
This results in the following functionality:
In React, however we don't have to interact with the browser's event loop in
raw JavaScript as React provides a way for us to handle events using .
For instance, to listen for the event from the (rather unimpressive)
demo above in React, we'll set the prop (notice the camelcasing
of the event name).
90
React provides a lot of we can set to listen for different browser
events, such as click, touch, drag, scroll, selection events, and many more
(see the events (https://facebook.github.io/react/docs/events.html)
documentation for a list of all of them).
91
To see some of these in action, the following is a small demo of some of the
we can pass on our elements. Each text element in the list set the prop
it lists. Try playing around with the list and seeing how the events are called
and handled within the element (all events are set on the text, not the list
item):
onMouseMove
onMouseUp
onMouseDown
onClick
onDoubleClick
onMouseLeave
onTouchStart
onTouchEnd
We'll be using the prop quite a bit all throughout our apps quite a
bit, so it's a good idea to be familiar with it. In our activity list header, we have
a search icon that we haven't hooked up yet to show a search box.
92
Let's update it a bit so that we can pass dynamic prop to the
element
93
When the user clicks on the
element, we'll want to run a function to update the state of the
component so the object gets updated. Using the
handler, this is pretty simple.
Let's make this component stateful (it needs to track if the search field
should be showing or not). We can convert our component to be stateful
using the function:
94
What is a function?
In JavaScript, the function is a function that runs when an
object is created. It returns a reference to the Object function that
created the instance's .
In plain English, a constructor function is the function that runs when the
JavaScript runtime creates a new object. We'll use the constructor method
to set up instance variables on the object as it runs right when the object
is created.
When using the class syntax to create an object, we have to call the
method before any other method. Calling the function
calls the parent class's function. We'll call it with the same
arguments as the function of our class is called with.
When the user clicks on the button, we'll want to update the state to say that
the flag gets updated. Since we'll want the user to be able to
close/hide the field after clicking on the search icon for a second
time, we'll toggle the state rather than just set it to true.
95
Let's add an if statement to update if
is
Finally, we can attach a click handler (using the prop) on the icon
element to call our new method. The entire updated source for
our component looks like this:
96
97
Try clicking on the search icon and watch the input field appear and
disappear (the animation effect is handled by CSS animations).
Input events
Whenever we build a form in React, we'll use the input events offered by
React. Most notably, we'll use the and props most
often.
Let's update our search box demo to capture the text inside the search field
when it updates. Whenever an field has the prop set,
it will call the function every time the field changes. When we click on it and
start typing, the function will be called.
Using this prop, we can capture the value of the field in our state.
98
Rather than updating our component, let's create a new child
component to contain a element. By moving the form-handling
responsibilities to it's own form, we can simplify the code and we
can call up to the parent of the header when our user submits the form (this
is a usual React pattern).
Now, we already have the HTML for the form written in the
component, so let's grab that from our component and return it from
our function:
99
Now that we've moved some code from the component to the
, let's update its method to incorporate the
100
Notice that we lost the styles on our field. Since we no longer have
the state in our new component, we can't use it to style the
any longer. However, we can pass a prop from our
component that tells the to render the input as visible.
101
In case you forgot to include package in your page
just add the following tag in your page
102
Now we have our styles back on the element, let's add the
functionality for when the user types in the search box, we'll want to capture
the value of the search field. We can achieve this workflow by attaching the
prop to the element and passing it a function to call
every time the element is changed.
103
When we type in the field, the function will be called.
We'll keep track of the value of the form by updating the state. In the
function, we can call directly to to
update the state of the component.
104
Controlled vs. uncontrolled
We're creating what's known as an uncontrolled component as we're not
setting the value of the element. We can't provide any
validation or post-processing on the input text value as it stands right
now.
105
As of now, we have no way to actually submit the form, so our user's can't
really search. Let's change this. We can capture the form submission by using
the prop on the element.
106
Now when we type into the field and press enter, the
function gets called with the event object.
So... great, we can submit the form and stuff, but when do we actually do the
searching? For demonstration purposes right now, we'll pass the search text
up the parent-child component chain so the can decide what to
search.
107
When the form is submitted, we can call this function directly from the
. Since we're keeping track of the search text in our state, we can call
the function with the value in the state so the
function only gets the value and doesn't need to deal with an event.
Now, when the user presses enter we can call this function
passed in the by our component.
108
Now we have a search form component we can use and reuse across our app.
Of course, we're not actually searching anything yet. Let's fix that and
implement search.
Implementing search
To implement search in our component, we'll want to pass up the search
responsibility one more level from our component to a container
component we'll call .
109
First things first, let's implement the same pattern of passing a callback to a
parent component from within a child component from the to the
component.
110
111
In any case, our component is essentially a copy of our
component we previously built on day 7. Make sure
to include the component in your page. Also
don't forget to include in your file as it's used by
to format dates. Add the following tag
in your page
112
Since the component doesn't control the content listing, the
component does, we have to pass the responsibility one more level up, as
we're defining here.
113
All we did here was add a function and pass it to the header.
Now when the user types in the search box, the function on
our component will be called.
114
Now we have a 3-layer app component that handles search from a nested
child component. We jumped from beginner to intermediate with this post.
Pat yourself on the back. This was some hefty material. Make sure you
understand this because we'll use these concepts we covered today quite
often.
In the next section, we'll jump out and look at building pure components.
115
Pure Components
Edit this page on Github (https://github.com/fullstackreact/30-days-of-react/blob/master/day-11/post.md)
We've looked at a few different ways to build react components. One method
we left out up through this point is the stateless component/functional
method of building React components.
As we've seen up through this point, we've only worked through building
components using the and methods.
For more performance and simplicity, React also allows us to create pure,
stateless components using a normal JavaScript function.
Pure components are the simplest, fastest components we can write. They
are easy to write, simple to reason about, and the quickest component we
can write. Before we dive into why these are better, let's write one, or heck a
couple!
116
So they are just functions, right? Yep! Since they are just functions, it's really
easy to test using pure JavaScript. The idea is that if React knows the
that are sent into a component, it can be deterministic in knowing if it has to
rerender or not. The same props in equal the same output virtual DOM.
117
For instance, let's say we want to rewrite our original component
using functional components as we want to give our users a dynamic way to
set their own clock styles (24 hour clock vs. 12, different separators, maybe
they don't want to display the seconds, etc).
We can break up our clock into multiple components where we can use each
block of time as an individual component. We might break them up like so:
With these, we can place individual components as through they are full-
blown React components (they are):
Minute: 12
Second: 51
118
We can refactor our clock component to accept a string and break up
this string selecting only the components our user is interested in showing.
There are multiple ways we can handle this, like forcing the logic into the
component or we can create another stateless component that
accepts a format string. Let's do that (easier to test):
This is a little ugly with the and thingie in there. React gives
us some helpers for mapping over children and taking care of handling the
unique for each child through the object.
119
We can now render the clock in a custom format:
120
Not only is our component much simpler, but it's so much easier to
test. It also will help us transition to using a data state tree, like Flux/Redux
frameworks, but more on those later.
16:01:11 pm
You might say why not use a functional component? Well, some of the
disadvantage of using a functional component are some of the advantages:
121
Overall, it's a really good idea to try to prefer using functional components
over their heavier cousins. When we get to talking about
data management in React, we'll see how we can use these presentational
components with data as pure .
Nice work today. We've successfully achieved React rank after today. We now
know the three ways to make a React Component.
Tomorrow, we'll get set up using/building React apps with the package
management tool shipped by the React team: .
122
create-react-app
Edit this page on Github (https://github.com/fullstackreact/30-days-of-react/blob/master/day-12/post.md)
The React team noticed that there is a lot of configuration required (and the
community helped bloat -- us included) to run a React app. Luckily, some
smart folks in the React team/community got together and built/released an
official generator app that makes it much easier to get up and running
quickly.
Packaging
So far in this course, we've only been working with writing our components
in a single script. Although it's great for simplicity, it can be difficult to share
components amongst multiple developers. A single file is also pretty difficult
to write complex applications.
Instead, we'll set up a build tool for our applications using a very popular
packaging tool called create-react-app
(https://github.com/facebookincubator/create-react-app). The tool
provides a great place to start out developing our applications without
needing to spend too much time working on setting up our build tooling.
In order to use it, we'll need to start out by installing it. We can use or
to install :
123
create-react-app
The create-react-app (https://github.com/facebookincubator/create-react-
app) project is released through Facebook helps us get up and running
quickly with a React app on our system with no custom configuring required
on our part.
124
With installed globally, we'll be able to use the
command anywhere in our terminal.
In terminal, we can create a new React application using the command and
adding a name to the app we want to create.
125
Let's start our app in the browser. The package comes with
a few built-in scripts it created for us (in the file). We can start
editing our app using the built-in webserver using the command:
126
This command will open a window in Chrome to the default app it created for
us running at the url: http://localhost:3000/ (http://localhost:3000/).
Let's edit the newly created app. Looking at the directory structure it
created, we'll see we have a basic node app running with a
and a few files in the directory that comprise our
running app.
127
Let's open up the file and we'll see we have a very basic
component that should all look familiar. It has a simple render function which
returns the result we see in the Chrome window.
128
Let's look at a few of the features enables for us.
We've used multiple components in the past. Let's pull in the example we
walked through on day-4 with a header and content (slightly simplified --
changing the className from to and removing the
inner component):
We could define the and the component in the same file, but
as we discussed, that becomes pretty cumbersome. Instead, let's create a
directory called in the directory ( ) and
create two files called and in there:
Now, let's write the two components in their respective file. First, the
components in :
129
And now let's write the component in the
file:
130
Now we can these two component from our file. Let's
update our by adding these two statements:
Here, we're using named exports to pull in the two components from their
respective files in .
By convention, if we only have a single export from these files, we can use the
syntax so we can remove the surrounding the named
export. Let's update each of these respective files to include an extra line at
the end to enable the default import:
131
and the component:
Now we can update our import of the two components like so:
Using this knowledge, we can now also update our components by importing
the named class and simplify our definition of the class file again.
Let's take the component in :
132
Shipping
We'll get to deployment in a few weeks, but for the time being know that the
generator created a build command so we can create minified, optimize
versions of our app that we can upload to a server.
We can build our app using the command in the root of our
project:
133
With that, we now have a live-reloading single-page app (SPA) ready for
development. Tomorrow, we'll use this new app we built diving into
rendering multiple components at run-time.
134
Repeating Elements
Edit this page on Github (https://github.com/fullstackreact/30-days-of-react/blob/master/day-13/post.md)
Up through this point, we've been building a basic application without any
external data. Before we get there (we'll start on this functionality tomorrow),
let's look over something we glossed over in the previous two weeks:
Repeating elements
We've already seen this before where we've iterated over a list of objects and
render multiple components on screen. Before we add too much complexity
in our app with loading external data, today we'll take a quick peek at how to
repeat components/elements in our app.
Since JSX is seen as plain JavaScript by the browser, we can use any ole'
JavaScript inside the template tags in JSX. We've already seen this in action.
As a quick demo:
135
10
100
Notice the things inside of the template tags look like simple JavaScript.
That's because it is just JavaScript. This feature allows us to use (most) native
features of JavaScript inside our template tags including native iterators,
such as and .
Let's see what we mean here. Let's convert the previous example's value
from a single integer to a list of integers:
We can map over the variable here inside our components and return a list
of React components that will build the virtual DOM for us.
136
What is the function?
1
10
100
1000
Let's update the app we created on day 12 with our component here.
Let's open up our file and replace the content of the
component with this source. Cleaning up a few unused variables and your
should look similar to this:
137
Starting the app again with the command generated by the
command: , we can see the app is working in the browser!
138
For performance reasons, React uses the virtual DOM to attempt to limit the
number of DOM elements that need to be updated when it rerenders the
view. That is if nothing has changed, React won't make the browser update
anything to save on work.
This feature is really fantastic for building web applications, but sometimes
we have to help React out by providing unique identifiers for nodes. Mapping
over a list and rendering components in the map is one of those times.
Children
We talked about building a parent-child relationship a bit earlier this week,
but let's dive a bit more into detail about how we get access to the children
inside a parent component and how we can render them.
139
We can use the object to map over a list of React objects and
let React do this heavy-lifting. The result of this is a much cleaner
component (not perfect, but functional):
140
141
React.cloneElement
We have yet to talk about the function, so let's look
at it briefly here. Remember WWWWWAAAAAYYYYY back on day 2 we
looked at how the browser sees JSX? It turns it into JavaScript that looks
similar to:
Rather than creating a new component instance (if we already have one),
sometimes we'll want to copy it or add custom props/children to the
component so we can retain the same props it was created with. We can
use to handle this for us.
Up through this point, we've only dealt with local data, not really focusing on
remote data (although we did briefly mention it when building our activity
feed component). Tomorrow we're going to get into interacting with a server
143
so we can use it in our React apps.
144
Fetching Remote Data
Edit this page on Github (https://github.com/fullstackreact/30-days-of-react/blob/master/day-14/post.md)
Our apps, until this point have largely been static. Even the data we displayed
from Github was static data included in our project. Our apps are really only
as interesting as the data we use, so let's make our apps more interesting.
When the browser parses the DOM tree, as it encounters remote files (such
as and tags), the browser will request these files (in
parallel), but will execute them synchronously (so as to maintain their order
they are listed in the source).
What if we want to get some data from off-site? We'll make requests for data
that's not available at launch time to populate data in our app. However, it's
not necessarily that easy to do because of the asynchronous nature of
external API requests.
145
Essentially, what this means is that we'll have to handle with JavaScript code
after an unknown period of time as well actually make an HTTP request.
Luckily for us, other people have dealt with this problem for a long time and
we now have some pretty nice ways of handling it.
Starting with handling how we'll be making an HTTP request, we'll use a
library (called , which is also a web standard
(https://fetch.spec.whatwg.org/), hopefully) to make the http requesting
easier to deal with.
Fetch
In order to use fetch, we'll need to install the library in our app we previously
created. Let's open up a terminal window again and use to install the
library (an implementation of ). In the same directory
where we created our application, let's call:
146
With the library installed, we can make a request to an off-site server. In
order to get access to the library, we'll need to the package in
our script. Let's update the top few lines of our file adding the
second line:
We'll pick up with tomorrow. Good job getting through week two
and see you tomorrow!
147
Introduction to Promises
Edit this page on Github (https://github.com/fullstackreact/30-days-of-react/blob/master/day-15/post.md)
What is a promise
As defined by the Mozilla, a object is used for handling
asynchronous computations which has some important guarantees that are
difficult to handle with the callback method (the more old-school method of
handling asynchronous code).
For instance, consider the following synchronous code where we print out
the current time in the JavaScript console:
Suppose we have a method that handles getting the current time for the
clock called that fetches the current time from a remote
server. We'll represent this now with a that returns the time
(like it's making a request to a slow API):
Our log value will return the timeout handler id, which is
definitely not the current time. Traditionally, we can update the code using a
callback to get called when the time is available:
149
What if there is an error with the rest? How do we catch the error and define
a retry or error state?
Now, what if we want to make a request based upon the first request's value?
As a short example, let's reuse the function inside again (as
though it were a second method, but allows us to avoid adding another
complex-looking function):
150
Dealing with asynchronousity in this way can get complex quickly. In
addition, we could be fetching values from a previous function call, what if we
only want to get one... there are a lot of tricky cases to deal with when
dealing with values that are not yet available when our app starts.
Enter Promises
Using promises, on the other hand helps us avoid a lot of this complexity
(although is not a silver bullet solution). The previous code, which could be
called spaghetti code can be turned into a neater, more synchronous-looking
version:
151
This previous source example is a bit cleaner and clear as to what's going on
and avoids a lot of tricky error handling/catching.
To catch the value on success, we'll use the function available on the
instance object. The function is called with whatever the
return value is of the promise itself. For instance, in the example above, the
function resolves with the value (on
successful completion) and calls the function on the return value
(which is another promise) and so on and so forth.
To catch an error that occurs anywhere in the promise chain, we can use the
method.
152
We're using a promise chain in the above example to create a
chain of actions to be called one after another. A promise
chain sounds complex, but it's fundamentally simple.
Essentially, we can "synchronize" a call to multiple
asynchronous operations in succession. Each call to is
called with the previous function's return value.
Single-use guarantee
A promise only ever has one of three states at any given time:
pending
fulfilled (resolved)
rejected (error)
A pending promise can only ever lead to either a fulfilled state or a rejected
state once and only once, which can avoid some pretty complex error
scenarios. This means that we can only ever return a promise once. If we
want to rerun a function that uses promises, we need to create a new one.
Creating a promise
153
We can create new promises (as the example shows above) using the
constructor. It accepts a function that will get run with two parameters:
Recalling our function from above, we can see that we call the
function if the request succeeded and call the function if the
method returns an error condition.
Now that we know what promises are, how to use, and how to create them,
we can actually get down to using the library we installed yesterday.
dd
154
Displaying Remote Data
Edit this page on Github (https://github.com/fullstackreact/30-days-of-react/blob/master/day-16/post.md)
As of today, we've worked through promises, built our app using the
packager, installed our remote object fetching library ( ) and
we're finally ready to integrate remote data into our application.
Fetching data
Let's get into using the library we installed on day 14 (/articles/30-
days-of-react/14-ajax).
For simplicity purposes, let's break out our demo from yesterday where we
fetched the current time from an API server:
155
This demo react component makes a request to the API server and reports
back the current time from it's clock. Before we add the call to fetch, let's
create a few stateful components we'll use to display the time and update the
time request.
First, the basis of the wrapper component which will show and fetch the
current time looks like the following. Let's copy and paste this code into our
app at :
156
157
The previous component is a basic stateful React component as we've
created. Since we'll want to show a form, we've included the intended usage
of the let's create next.
Now let's add content. We'll want our to take the role of allowing
the user to switch between timezones in their browser. We can handle this
by creating a stateful component we'll call the . Our
component might look like the following:
158
159
With these Components created, let's load up our app in the browser after
running it with and we'll see our form (albeit not incredibly
beautiful yet). Of course, at this point, we won't have a running component as
we haven't implemented our data fetching. Let's get to that now.
160
Fetching data
Fetching data
As we said yesterday, we'll use the API with promise support. When
we call the method, it will return us a promise, where we can handle
the request however we want. We're going to make a request to our now-
based API server (so start-up might be slow if it hasn't been run in a while).
We're going to be building up the URL we'll request as it represents the time
query we'll request on the server.
The chronic api server accepts a few variables that we'll customize in the
form. It will take the timezone to along with a chronic message. We'll start
simply and ask the chronic library for the timezone and the current time
( ):
Now, when we call , the URL of the next request will be returned
for us. Now, finally, let's implement our function. The
function accepts a few arguments that can help us customize our requests.
161
The most basic request can just take a single URL endpoint. The return
value on is a promise object, that we explored in-depth yesterday.
The final piece of our project today is getting the data back from the form to
update the parent component. That is, when the user updates the values
from the component, we'll want to be able to access the data in the
component. The component already handles this process for
us, so we just need to implement our form functions.
When a piece of state changes on the form component, it will call a prop
called . By defining this method in our component, we can
get access to the latest version of the form.
In fact, we'll just call to keep track of the options the form allows
the user to manipulate:
162
Finally, when the user submits the form (clicks on the button or presses enter
in the input field), we'll want to make another request for the time. This
means we can define our prop to just call the
method:
Try playing around with the demo and passing in different chronic options.
It's actually quite fun.
In any case, today we worked on quite a bit to get remote data into our app.
However, at this point, we only have a single page in our single page app.
What if we want to show a different page in our app? Tomorrow, we're going
to start adding multiple pages in our app so we can feature different views.
163
164
Client-side Routing
Edit this page on Github (https://github.com/fullstackreact/30-days-of-react/blob/master/day-17/post.md)
Most, if not all of our applications will have multiple views in our
single-page application. Let's dive right into creating multiple
views for our applications using React Router.
We've made it through 16 days already! Pat yourself on the back... but not for
too long... there is still a lot more.
Right now, our app is limited to a single page. It's pretty rare to find any
complex application that shows a single view. For instance, an application
might have a login view where a user can log in or a search results page that
shows a user a list of their search results. These are two different views with
two different page structures.
Let's see how we can change that with our app today.
165
With installed, we'll import a few packages from the library and
update our app architecture. Before we make those updates, let's take a step
back and from a high level look at how and why we architect our application
this way.
Conceptually with React, we've seen how we can create tree structures using
components and nested components. Using this perspective with a single
page app with routes, we can think of the different parts of a page as
children. Routing in a single page app from this perspective is the idea that
we can take a part of a subtree and switch it out with another subtree. We
can then dynamically switch out the different trees in the browser.
In other words, we'll define a React component that acts as a root component
of the routable elements. We can then tell React to change a view, which can
just swap out an entire React component for another one as though it's a
completely different page rendered by a server.
We'll take our component and define all of the different routes we can
make in our app in this component. We'll need to pull some components
from the package. These components we'll use to set up this
structure are as follows:
/
166
This is the component we'll use to define the root or the routing tree. The
component is the component where React will replace it's
children on a per-route basis.
From the app we created a few days ago's root directory, let's update our
to import these modules. We'll import the using a
different name syntax via ES6:
Now let's define our first route. To define a route, we'll use the
component export from and pass it a few props:
Let's define the a route at the root path with a stateless component that
just displays some static content:
167
Welcome home
Loading this page in the browser, we can see we get our single route at the
root url. Not very exciting. Let's add a second route that shows an about page
at the URL.
168
Welcome home
In our view we'll need to add a link (or an anchor tag -- ) to enable our
users to travel freely between the two different routes. However, using the
tag will tell the browser to treat the route like it's a server-side route.
Instead, we'll need to use a different component (surprise) called: .
Wait a minute... we don't quite want both routes to show up... This happens
because the react router will render all content that matches the path (unless
otherwise specified). For this case, react router supplies us with the
component.
The component will only render the first matching route it finds.
Let's update our component to use the component. As react router
will try to render both components, we'll need to specify that we only want an
match on the root component.
170
Welcome home
Go to about
Showing views
171
Although this is a limited introduction, we could not leave the discussion of
dealing with react router without talking about the different ways we can get
subcomponents to render.
We've already seen the simplest way possible, using the prop,
however there is a more powerful method using a prop called . The
prop is expected to be a function that will be called with the
object along with the and route configuration.
172
173
Home is underneath me
Welcome home
Go to about
Now we have multiple pages in our application. We've looked at how we can
render these routes through nested components with just a few of the
exports from .
https://github.com/reactjs/react-router/tree/master/docs
(https://github.com/reactjs/react-router/tree/master/docs)
fullstack react routing (https://fullstackreact.com)
174
175
Introduction to Flux
Edit this page on Github (https://github.com/fullstackreact/30-days-of-react/blob/master/day-18/post.md)
As our applications get bigger and more complex, we'll need a better data
handling approach. With more data, we'll have more to keep track of.
Our code is required to handle more data and application state with new
features. From asynchronous server responses to locally-generated,
unsynchronized data, we have to not only keep track of this data, but also tie
it to the view in a sane way.
Recognizing this need for data management, the Facebook team released a
pattern for dealing with data called Flux
(https://facebook.github.io/flux/docs/overview.html).
Today, we're going to take a look at the Flux architecture, what it is and why
it exists.
What is flux
Flux is a pattern for managing how data flows through a React application. As
we've seen, the preferred method of working with React components is
through passing data from one parent component to it's children
176
components. The Flux pattern makes this model the default method for
handling data.
There are three distinct roles for dealing with data in the flux methodology:
Dispatcher
Stores
Views (our components)
The major idea behind Flux is that there is a single-source of truth (the
stores) and they can only be updated by triggering actions. The actions are
responsible for calling the dispatcher, which the stores can subscribe for
changes and update their own data accordingly.
When a dispatch has been triggered, and the store updates, it will emit a
change event which the views can rerender accordingly.
This may seem unnecessarily complex, but the structure makes it incredibly
easy to reason about where our data is coming from, what causes it's
changes, how it changes, and lets us track specific user flows, etc.
Implementations
Although we can create our own flux implementation, many have already
created some fantastic libraries we can pick from.
It can be pretty intense trying to pick the right choice for our applications.
Each has their own features and are great for different reasons. However, to a
large extent, the React community has focused in on using another flux tool
called Redux (http://redux.js.org/).
Redux (http://redux.js.org/)
Redux is a small-ish library that takes it's design inspiration from the Flux
pattern, but is not itself a pure flux implementation. It provides the same
general principles around how to update the data in our application, but in
slightly different way.
Unlike Flux, Redux does not use a dispatcher, but instead it uses pure
functions to define data mutating functions. It still uses stores and actions,
which can be tied directly to React components.
178
Updates are made with pure functions (in reducers)
is a read-only property
is the single source of truth (there is only one in a Redux
app)
One big difference with Redux and Flux is the concept of middleware. Redux
added the idea of middleware that we can use to manipulate actions as we
receive them, both coming in and heading out of our application. We'll
discuss them in further detail in a few days.
In any case, this is a lot of introduction to the flux pattern. Tomorrow we'll
actually start moving our data to use Redux.
179
Data Management with Redux
Edit this page on Github (https://github.com/fullstackreact/30-days-of-react/blob/master/day-19/post.md)
Yesterday, we discussed (in light detail) the reason for the Flux pattern, what
it is, the different options we have available to us, as well as introduced Redux
(http://redux.js.org/).
Today, we are going to get back to code and on to adding Redux in our app.
The app we're building with it right now is bare-bones simple, which will just
show us the last time the page fetched the current time. For simplicity for
now, we won't call out to a remote server, just using the JavaScript
object.
The first thing we'll have to do to use Redux is install the library. We can use
the package manager to install . In the root directory of our app
we previously built, let's run the command to install redux:
We'll also need to install another package that we'll use with redux, the
that will help us tie together and :
180
Configuration and setup
The next bit of work we need to do is to set up Redux inside of our app. We'll
need to do the following to get it set up:
1. Define reducers
2. Create a store
3. Create action creators
4. Tie the store to our React views
5. Profit
Precursor
We'll talk terminology as we go, so take this setup discussion lightly
(implementing is more important to get our fingers moving). We'll
restructure our app just slightly (annoying, I know... but this is the last time)
181
so we can create a wrapper component to provide data down through our
app.
When we're complete, our app tree will have the following shape:
We'll include a few routes with the statement to ensure only one
shows up at a time.
182
In addition, we'll need to create a new container we'll call which will
wrap our entire component and make the store available to the rest
of the app. Let's create the file:
For the time being, we'll use a placeholder component here, but we'll replace
this content as we talk about the store. For now, let's export something:
Finally, let's update the route that we render our app in the file
to use our new container instead of the it previously used.
Adding in Redux
Now with a solid app structure in place, we can start to add in Redux. The
steps we'll take to tie in some Redux structure are generally all the same for
most every application we'll build. We'll need to:
Let's setup the structure to allow us to add redux. We'll do almost all of our
work in a directory. Let's create that directory.
In the Redux pattern, unlike flux we are only handling one global store for the
entire application. This makes things much easier to deal with as there's a
single place for the data of our application to live.
184
In the function, we're defining the first argument to start out as the initial
state (the first time it runs, the is called with no arguments, so it
will always return the on the first run).
That's the rootReducer for now. As it stands right now, the state always will
be the same value as the initialState. In our case, this means our data tree has
a single key of .
What is an action?
The second argument here is the action that gets dispatched from the store.
We'll come back to what that means exactly shortly. For now, let's look at the
action.
At the very minimum, an action must include a key. The key can
be any value we want, but it must be present. For instance, in our application,
we'll occassionally dispatch an action that we want to tell the store to get the
new current time. We might call this action a string value of .
The action we might dispatch from our store to handle this update looks like:
185
As we'll by typing this string a lot and we want to avoid a possible mispelling
somewhere, it's common to create a file that exports the action
types as constants. Let's follow this convention and create a
file:
When we want to send data along with our action, we can add any keys we
want to our action. We'll commonly see this called , but it can be
called anything. It's a convention to call additional information the .
Our action will send a payload with the new current time.
Since we want to send a serializable value with our actions, we'll send the
string value of the new current time.
Back in our reducer, we can check for the action type and take the
appropriate steps to create the next state. In our case, we'll just store the
. If the of the action is , we'll return the new
currentTime (from our action payload) and the rest of the state (using the
ES6 spread syntax):
186
Remember, the reducers must return a state, so in the default case, make
sure to return the current state at the very minimum.
Keep it light
Since the reducer functions run everytime an action is dispatched, we
want to make sure these functions are as simple and fast as possible. We
don't want them to cause any side-effects or have much delay at all.
We'll handle our side-effects outside of the reducer in the action creators.
Before we look at action creators (and why we call them action creators), let's
hook up our store to our application.
188
We don't actually return anything in our store quite yet, so let's actually
create the store using the function we imported from
redux:
189
If we load our page in the browser, we'll see we have one giant error and no
page gets rendered.
The error redux is giving us is telling us that we don't have a reducer inside
our store. Without a reducer, it won't know what to do with actions or how to
create the state, etc. In order to move beyond this error, we'll need to
reference our rootReducer we created.
190
Connecting the view (cont'd)
Everything in our app is set-up to use Redux without too much overhead.
One more convenience that offers is a way to bind pieces of the state
tree to different components using the function exported by the
package.
191
In our demo's case, the prop in the component will be
mapped to the state tree key at . Let's update the
component to show the value in the :
Although this demo isn't very interesting, it shows we have our app set
up with our committed to the global state and our view components
mapping the data.
Welcome home!
Current time: Thu Feb 27 2020 16:01:42 GMT0600 (CST)
Tomorrow we're going to start triggering updates into our global state
through action creators as well as work through combining multiple redux
modules together.
192
Redux actions
Edit this page on Github (https://github.com/fullstackreact/30-days-of-react/blob/master/day-20/post.md)
With Redux in place, let's talk about how we actually modify the
Redux state from within our applications.
Yesterday we went through the difficult part of integrating our React app
with Redux. From here on out, we'll be defining functionality with our Redux
setup.
As it stands now, we have our demo application showing the current time.
But there currently isn't any way to update to the new time. Let's modify this
now.
Triggering updates
Recall that the only way we can change data in Redux is through an action
creator. We created a redux store yesterday, but we haven't created a way for
us to update the store.
Welcome home!
Current time: Thu Feb 27 2020 16:01:45 GMT0600 (CST)
What we want is the ability for our users to update the time by clicking on a
button. In order to add this functionality, we'll have to take a few steps:
193
1. Create an actionCreator to dispatch the action on our store
2. Call the actionCreator of an element
3. Handle the action in the reducer
Yesterday, we discussed what actions are, but not really why we are using
this thing called actionCreators or what they are.
As a quick review, our actions can be any object value that has the key.
We can send data along with our action (conventionally, we'll pass extra data
along as the of an action).
Now we need to dispatch this along our . One way we could do that is
by calling the function.
194
However, this is pretty poor practice. Rather than dispatch the action
directly, we'll use a function to return an action... the function will create the
action (hence the name: actionCreator). This provides us with a better testing
story (easy to test), reusability, documentation, and encapsulation of logic.
Now if we call this function, nothing will happen except an action object is
returned. How do we get this action to dispatch on the store?
195
Now the function will be passed in as a prop and will call
when we fire the action. Let's update our component
so the user can press a button to update the time.
Welcome home!
Current time: Thu Feb 27 2020 16:01:45 GMT0600 (CST)
Update time
196
Although this example isn't that exciting, it does showcase the features of
redux pretty well. Imagine if the button makes a fetch to get new tweets or
we have a socket driving the update to our redux store. This basic example
demonstrates the full functionality of redux.
Multi-reducers
As it stands now, we have a single reducer for our application. This works for
now as we only have a small amount of simple data and (presumably) only one
person working on this app. Just imagine the headache it would be to develop
with one gigantic switch statement for every single piece of data in our apps...
Ahhhhhhhhhhhhhh...
Redux to the rescue! Redux has a way for us to split up our redux reducers
into multiple reducers, each responsible for only a leaf of the state tree.
Let's say that we (perhaps more realistically) want to keep track of the
current user. Let's create a redux module in... you guessed it:
:
197
Let's update our function to take these branches into
account, using the to separate out the two branches
198
Let's also update our component function to read it's
value from the reducer
199
Now we can use the actionCreators to call and just like the
action creator.
Phew! This was another hefty day of Redux code. Today, we completed the
circle between data updating and storing data in the global Redux state. In
addition, we learned how to extend Redux to use multiple reducers and
actions as well as multiple connected components.
200
Redux Middleware
Edit this page on Github (https://github.com/fullstackreact/30-days-of-react/blob/master/day-21/post.md)
Redux middleware
Middleware generally refers to software services that "glue together"
separate features in existing software. For Redux, middleware provides a
third-party extension point between dispatching an action and handing the
action off to the reducer:
Let's take the case of handling asynchronous requests, like an HTTP call to a
server. Middleware is a great spot to do this.
Middleware sits between the action and the reducer. It can listen for all
dispatches and execute code with the details of the actions and the current
states. Middleware provides a powerful abstraction. Let's see exactly how we
can use it to manage our own.
Continuing with our redux work from yesterday, let's build our
middleware to fetch the current time from the server we used a few days ago
to actually GET the time from the API service.
Before we get too much further, let's pull out the work from the
in the file out to it's own file. We left the root
reducer in a state where we kept the work in the root reducer.
More conventionally, we'll move these in their own files and use the
file (which we called ) to hold just the main
combination reducer.
First, let's pull the work into it's own file in . We'll
export two objects from here (and each reducer):
202
With our out of the root reducer, we'll need to update the
file to accept the new file into the root reducer. Luckily, this is
pretty easy:
203
Lastly, let's update the function to pull the rootReducer and
initial state from the file:
Back to middleware
Middleware is basically a function that accepts the , which is expected
to return a function that accepts the function, which is expected to
return a function which accepts an action. Confusing? Let's look at what this
means.
204
Befuddled about this middleware thing? Don't worry, we all are the first time
we see it. Let's peel it back a little bit and destructure what's going on. That
description above could be rewritten like the following:
We don't need to worry about how this gets called, just that it does get called
in that order. Let's enhance our so that we do actually log
out the action that gets called:
Our middleware causes our store to, when every time an action is called,
we'll get a with the details of the action.
In order to apply middleware to our stack, we'll use this aptly named
function as the third argument to the
method.
205
To apply middleware, we can call this function in the
method. In our file, let's update
the store creation by adding a call to :
Now our middleware is in place. Open up the console in your browser to see
all the actions that are being called for this demo. Try clicking on the
button with the console open...
Welcome home!
Current time: Thu Feb 27 2020 16:01:49 GMT0600 (CST)
Update time
206
marker. For instance, we can have a object on the action with a of
. We can use this to ensure our middleware does not handle any
actions that are not related to API requests:
If an action does have a meta object with a type of , we'll pick up the
request in the .
Let's pass in the URL to our object for this request. We can even accept
parameters from inside the call to the action creator:
When we press the button to update the time, our will catch
this before it ends up in the reducer. For any calls that we catch in the
middleware, we can pick apart the meta object and make requests using
207
these options. Alternatively, we can just pass the entire sanitized object
through the API as-is.
1. Find the request URL and compose request options from meta
2. Make the request
3. Convert the request to a JavaScript object
4. Respond back to Redux/user
Let's take this step-by-step. First, to pull off the and create the
to pass to . We'll put these steps in the comments in
the code below:
208
We have several options for how we respond back to the user in the Redux
chain. Personally, we prefer to respond with the same type the request was
fired off without the tag and placing the response body as the
of the new action.
In this way, we don't have to change our redux reducer to manage the
response any differently than if we weren't making a request.
We're also not limited to a single response either. Let's say that our user
passed in an callback to be called when the request was complete.
We could call that callback and then dispatch back up the chain:
209
The possibilities here are virtually endless. Let's add the to
our chain by updating it in the function:
210
Welcome home!
Current time: Thu Feb 27 2020 16:01:49 GMT0600 (CST)
Update time
Notice that we didn't have to change any of our view code to update how the
data was populated in the state tree. Pretty nifty, eh?
This middleware is pretty simplistic, but it's a good solid basis for building it
out. Can you think of how you might implement a caching service, so that we
don't need to make a request for data we already have? How about one to
keep track of pending requests, so we can show a spinner for requests that
are outstanding?
Awesome! Now we really are Redux ninjas. We've conquered the Redux
mountain and are ready to move on to the next step. Before we head there,
however... pat yourself on the back. We've made it through week 3!
211
212
Introduction to Testing
Edit this page on Github (https://github.com/fullstackreact/30-days-of-react/blob/master/day-22/post.md)
Okay, close your eyes for a second... wait, don't... it's hard to read with your
eyes closed, but imagine for a moment your application is getting close to
your first deployment.
It's getting close and it gets tiring to constantly run through the features in
your browser... and so inefficient.
Testing
When we talk about testing, we're talking about the process of automating
the process of setting up and measuring our assumptions against assertions
of functionality about our application.
When we talk about front-end testing in React, we're referring to the process
of making assertions about what our React app renders and how it responds
to user interaction.
Unit testing refers to testing individual pieces (or units, hence the name) of
our our code so we can be confident these specific pieces of code work as we
expect.
In React, Unit tests typically do not require a browser, can run incredibly
quickly (no writing to the DOM required), and the assertions themselves are
usually simple and terse.
Functional testing
Given a logged in user, the navbar renders a button with the text Logout
Given no logged in user, the navbar renders a button with the text Login
Integration testing
Finally, the last type of testing we'll look at is integration testing. This type of
testing tests the entire service of our application and attempts to replicate
the experience an end-user would experience when using our application.
214
On the order of speed and efficiency, integration testing is incredibly slow as
it needs to run expectations against a live, running browser, where as unit
and functional tests can run quite a bit faster (especially in React where the
functional test is testing against the in-memory virtual dom rather than an
actual browser render).
When testing React components, we will test both our expectations of what
is contained in the virtual dom as well as what is reflected in the actual dom.
The tools
We're going to use a testing library called called jasmine
(http://jasmine.github.io) to provide a readable testing language and
assertions.
As far as test running, there is a general debate around which test runner is
the easiest/most efficient to work with, largely between mocha
(https://mochajs.org) and jest (https://facebook.github.io/jest).
We're going to use Jest in our adventure in testing with React as it's the
official (take this with a grain of salt) test runner. Most of the code we'll be
writing will be in Jasmine, so feel free to use mocha, if it's your test library of
choice.
Tomorrow, we'll get our application set up with the testing tooling in place so
that we can start testing our application and be confident it works as we
expect. See you tomorrow!
215
216
Implementing Tests
Edit this page on Github (https://github.com/fullstackreact/30-days-of-react/blob/master/day-23/post.md)
Let's get our application set up to be tested. Since we're going to be using a
few different libraries, we'll need to install them before we can use them
(obviously).
Dependencies
We're going to use the following libraries:
jest/jest-cli
Jest (https://facebook.github.io/jest/) is the official testing framework
released by Facebook and is a fantastic testing framework for testing React
applications. It is incredibly fast, provides sandboxed testing environments,
support for snapshot testing, and more.
babel-jest/babel-preset-stage-0
217
We'll write our tests using the stage 0 (or ES6-edge functionality), so we'll
want to make sure our test framework can read and process our ES6 in our
tests and source files.
sinon
Sinon is a test utility library which provides a way for us to write spies, stubs,
and mocks. We'll discuss what these are when we need them, but we'll install
the library for now.
react-addons-test-utils/enzyme
The package contains testing utilities provided by
the React team.
react-test-renderer
The library allows us to use the snapshot feature from
the jest library. Snapshots are a way for Jest to serialize the rendered output
from the virtual DOM into a file which we can automate comparisons from
one test to the next.
redux-mock-store
The redux-mock-store (https://github.com/arnaudbenard/redux-mock-
store) library allows us to easily make a redux store for testing. We'll use it to
test our action creators, middleware, and our reducers.
To install all of these libraries, we'll use the following command in the
terminal while in the root directory of our projects:
218
Configuration
We'll also need to configure our setup. First, let's add an npm script that will
allow us to run our tests using the command. In our
file in the root of our project, let's add the script. Find the scripts key in
the file and add the command, like so:
Writing tests
Let's confirm that our test setup is working properly. Jest will automatically
look for test files in the entire tree in a directory called (yes, with
the underscores). Let's create our first directory in our
directory and create our first test file:
219
Timeline
An hour ago
Ate lunch
10 am
Read Day two article
10 am
Lorem Ipsum is simply dummy text of the printing and
typesetting industry.
2:21 pm
Lorem Ipsum has been the industry's standard dummy
text ever since the 1500s, when an unknown printer
took a galley of type and scrambled it to make a type
specimen book.
220
In the file, let's add
the describe block:
We can add our first test using the function. The function is
where we will set our expectations. Let's set up our tests with our first
expectations, one passing and one failing so we can see the difference in
output.
We'll look at the possible expectations we can set in a moment. First, let's run
our tests.
Executing tests
The package sets up a quality testing environment using
Jest automatically for us. We can execute our tests by using the or
script.
221
From this output, we can see the two tests with one passing test (with a
green checkmark) and one failing test (with the red x and a description of the
failure).
Let's update the second test to make it pass by changing the expectation to
:
222
Expectations
Jest provides a few global commands in our tests by default (i.e. things you
don't need to require). One of those is the command. The
command has a few expectations which we can call on it, including the two
we've used already:
etc.
223
The function takes a single argument: the value or function that
returns a value to be tested. For instance, our two tests we've already writen
pass the boolean values of and .
Now that we've written our first tests and confirmed our setup, we'll actually
get down to testing our Timeline component tomorrow. Great job today and
see you tomorrow!
224
Testing the App
Edit this page on Github (https://github.com/fullstackreact/30-days-of-react/blob/master/day-24/post.md)
Let's start with the component as it's the most complex in our
current app.
Timeline
An hour ago
Ate lunch
10 am
Read Day two article
10 am
Lorem Ipsum is simply dummy text of the printing and
typesetting industry.
2:21 pm
225
Lorem Ipsum has been the industry's standard dummy
text ever since the 1500s, when an unknown printer
took a galley of type and scrambled it to make a type
specimen book.
Testing
Let's open the file . We
left off with some dummy tests in this file, so let's clear those off and start
with a fresh describe block:
226
For every test that we write against React, we'll want to import react into our
test file. We'll also want to bring in the react test utilities:
Since we're testing the component here, we'll also want to bring
that into our workspace:
Let's write our first test. Our first assumption is pretty simple to test. We're
testing to make sure the element is wrapped in a class.
With every test we'll write, we'll need to render our application into the
working test document. The library provides a
function to do just this called :
227
If we run this test (even though we're not setting any expectations yet), we'll
see that we have a problem with the testing code. React thinks we're trying to
render an undefined component:
228
With that, our tests will pass (believe it or not). The TestUtils sets up an
expectation that it can find the component with the
class. If it doesn't find one, it will throw an error and our tests will fail.
229
With our one passing test, we've confirmed our test setup is working.
230
Better Testing with Enzyme
Edit this page on Github (https://github.com/fullstackreact/30-days-of-react/blob/master/day-25/post.md)
Timeline
231
Using Enzyme
We'll use Enzyme to make these tests easier to write and more readable.
Although this works, it's not quite the easiest test in the world to read. Let's
see what this test looks like when we rewrite it with Enzyme.
Rather than testing the complete component tree with Enzyme, we can test
just the output of the component. Any of the component's children will not
be rendered. This is called shallow rendering.
Enzyme makes shallow rendering super easy. We'll use the function
exported by Enzyme to mount our component.
232
Let's first configure use the adapter that makes it compatible with
React version 16. Create and add the following:
Now to render our component, we can use the method and store
the result in a variable. Then, we'll query the rendered component for
different React elements (HTML or child components) that are rendered
inside its virtual dom.
233
The entire assertion comprises two lines:
We can run our tests in the same manner as we did before using the
command (or the command):
Let's fill in these tests so that they pass against our existing
component.
235
Our title test is relatively simple. We'll look for the title element and confirm
the title is .
Shallow? Mount?
The rendering function only renders the component we're
testing specifically and it won't render child elements. Instead we'll have
to the component as the child won't be available in the
jsdom otherwise.
236
Running our tests, we'll see these two expectations pass:
Next, let's update our search button tests. We have two tests here, where one
requires us to test an interaction. Enzyme provides a very clean interface for
handling interactions. Let's see how we can write a test against the search
237
icon.
Again, since we're testing against a child element in our Timeline, we'll have
to the element. Since we're going to write two tests in a nested
block, we can write a before helper to create the anew
for each test so they are pure.
To test if the search input is hidden, we'll just have to know if the
class is applied or not. Enzyme provides a way for us to detect if a component
has a class or not using the method. Let's fill out the first test to
expect the search input doens't have the active class:
238
The tricky part about the second test is that we need to click on the icon
element. Before we look at how to do that, let's find it first. We can target it
by it's class on the wrapper:
Now that we have the icon we want to simulate a click on the element. Recall
that the method is really just a facade for browser events. That is,
a click on an element is just an event getting bubbled through the
component. Rather than controlling a mouse or calling on the
element, we'll simulate an event occurring on it. For us, this will be the
event.
239
Now we can set an expectation that the component has the
class.
240
241
What's the deal with ?
Before we close out for today, we should look at the interface of an Enzyme
shallow-rendered component (in our tests, the object). The Enzyme
documentation (http://airbnb.io/enzyme/docs/api/shallow.html) is
fantastic, so we'll keep this short.
Basically, when we use the function, we'll pass it a selector and it will
return a instance that wraps the found nodes. The
function can take a string, function, or an object.
When we pass strings into the function, we can pass CSS selectors or
the displayName of a component. For instance:
Finally, we can also pass it an object property selector object, which selects
elements by their key and values. For instance:
242
Take the case of the component. If we wanted to find the HTML of
the link class based on all the links available, we can write a test like this:
Phew! That's a lot of new information today, but look how quickly we wrote
our follow-up tests with Enzyme. It's much quicker to read and makes it
easier to discern what's actually happening.
Tomorrow we'll continue with our testing journey and walk through
integration testing our application.
243
Integration Testing
Edit this page on Github (https://github.com/fullstackreact/30-days-of-react/blob/master/day-26/post.md)
Today we'll write tests to simulate how users interact with our
application and will test the entire flow of our app in a live
browser.
We've reached the final part of our introduction to testing. We're going to
wrap up our testing section with integration testing. As a reminder of what
Integration testing is, it's the process of automating the experience that our
actual users experience as they use our application.
Integration testing
As we're integration testing, we'll need to have our app actually running as
we're going to have a browser launch and execute our application. We'll be
using an automation server called selenium (http://www.seleniumhq.org), so
244
we'll need to download it as well as a really nifty node automated testing
framework called Nightwatch (http://nightwatchjs.org).
Install
The easiest way to install selenium (http://docs.seleniumhq.org/download/)
is to download it through the the selenium website at:
http://docs.seleniumhq.org/download/
(http://docs.seleniumhq.org/download/).
We'll also need to install the command, which we can do with the
package manager. Let's install globally using the
flag:
Writing tests
We'll write our nightwatch tests in a directory. Let's start by writing a
test for handling the auth workflow. Let's write our test in a directory
(which matches the ) that we'll call .
The nightwatch tests can be set as an object of exports, where the key is the
description of the test and the value is a function with a reference to the
client browser. For instance, we'll set up four tests for our
test.
Updating our file with these four test functions look like
the following:
Let's write our first test to demonstrate this function. We're going to set up
nightwatch so that it launches the page, and clicks on the Login link in the
navbar. We'll take the following steps to do this:
247
1. We'll first call the function on browser to ask it to load a URL on
the page.
2. We'll wait for the page to load for a certain amount of time.
3. We'll find the Login link and click on it.
And we'll set up assertions along the way. Let's get busy! We'll ask the
to load the URL we set in our configuration file (for us, it's
)
Thats it. Before we get too far ahead, let's run this test to make sure our test
setup works. We'll need to open 3 terminal windows here.
In the first terminal window, let's launch selenium. If you downloaded the
file, you can start this with the command:
248
In the second window, we'll need to launch our app. Remember, the browser
we're going to launch will actually hit our site, so we need an instance of it
running. We can start our app up with the comamnd:
249
Finally, in the third and final terminal window, we'll run our tests using the
command.
250
When we run the command, we'll see a chrome window open up,
visit the site, and click on the login link automatically... (pretty cool, right?).
All of our tests pass at this point. Let's actually tell the browser to log a user
in.
Since the first step will run, the browser will already be on the login page. In
the second key of our tests, we'll want to take the following steps:
251
Running these tests again (in the third terminal window):
252
We can do a similar thing with the step from our browser. To
get a user to log out, we will:
253
254
As of now, you may have noticed that your chrome browsers haven't been
closing when the tests have completed. This is because we haven't told
selenium that we want the session to be complete. We can use the
command on the object to close the connection. This is why we
have the last and final step called .
Now let's run the entire suite and make sure it passes again using the
command:
255
One final note, if you're interested in a deeper set of selenium tutorials,
check out the free tutorials from guru99.com at
https://www.guru99.com/selenium-tutorial.html
(https://www.guru99.com/selenium-tutorial.html). They are pretty in-depth
and well done (in our opinion).
That's it! We've made it and have covered 3 types of testing entirely, from
low-level up through faking a real browser instance. Now we have the tools
to ensure our applications are ready for full deployment.
But wait, we don't actually have deployment figured out yet, do we? Stay
tuned for tomorrow when we start getting our application deployed into the
cloud.
256
Deployment Introduction
Edit this page on Github (https://github.com/fullstackreact/30-days-of-react/blob/master/day-27/post.md)
With our app all tested up through this point, it's time to get it up and live for
the world to see. The rest of this course will be dedicated to deploying our
application into production.
Production deployment
When talking about deployment, we have a lot of different options:
Hosting
Deployment environment configuration
Continuous Integration (CI, for short)
Cost cycles, network bandwidth cost
Bundle size
and more
We'll look at the different hosting options we have for deploying our react
app tomorrow and look at a few different methods we have for deploying our
application up. Today we're going to focus on getting our app ready for
deployment.
257
Ejection (from )
First things first... we're going to need to handle some customization in our
web application, so we'll need to run the command in the root
of our directory. This is a permanent action, which just means we'll be
responsible for handling customizations to our app structure for now on
(without the help of our handy ).
Webpack basics
Webpack is a module bundler with a ginormous community of users, tons of
plugins, is under active development, has a clever plugin system, is incredibly
fast, supports hot-code reloading, and much much more.
258
Although we didn't really call it out before, we've been using webpack this
entire time (under the guise of ). Without webpack, we wouldn't
have have been able to just write and expect our code to load. It
works like that because webpack "sees" the keyword and knows we
need to have the code at the path accessible when the app is running.
Webpack takes care of hot-reloading for us, nearly automatically, can load
and pack many types of files into bundles, and it can split code in a logical
manner so as to support lazy-loading and shrink the initial download size for
the user.
This is meaningful for us as our apps grow larger and more complex, it's
important to know how to manipulate our build tools.
The file is a giant file that contains all the JavaScript code our app
needs to run, including dependencies and our own files alike. Webpack has
it's own method of packing files together, so it'll look kinda funny when
looking at the raw source.
259
The module itself is encapsulated inside of a function that looks like this:
Each module of our web app is encapsulated inside of a function with this
signature. Webpack has given each of our app's modules this function
container as well as a module ID (in the case of , 254).
Here's what the variable declaration of looks like inside the chaos
of the Webpack module:
This looks quite strange, mostly due to the in-line comment that Webpack
provides for debugging purposes. Removing that comment:
260
Now, search for in this file.
If you open a new browser tab and plug in this address (your address will be
different... matching the name of the file webpack generated for you):
What about our CSS assets? Yep, everything is a module in Webpack. Search
for the string :
261
Webpack's didn't include any references to CSS. That's because
Webpack is including our CSS here via . When our app loads, this
cryptic Webpack module function dumps the contents of into
tags on the page.
Webpack, like other bundlers, consolidated all our JavaScript modules into a
single file. It could keep JavaScript modules in separate files, but this requires
some more configuration than provides out of the box.
Webpack takes this module paradigm further than other bundlers, however.
As we saw, it applies the same modular treatment to image assets, CSS, and
npm packages (like React and ReactDOM). This modular paradigm unleashes
a lot of power. We touch on aspects of that power throughout the rest of this
chapter.
Complex, right?
It's okay if you don't understand that out of the box. Building and
maintaining webpack is a complex project with lots of moving parts and it
often takes even the most experienced developers a while to "get."
We'll walk through the different parts of our webpack configuration that
we'll be working with. If it feels overwhelming, just stick with us on the
basics here and the rest will follow.
262
With our newfound knowledge of the inner workings of Webpack, let's turn
our attention back to our app. We'll make some modifications to our webpack
build tool to support multiple environment configurations.
Environment configuration
When we're ready to deploy a new application, we have to think about a few
things that we wouldn't have to focus on when developing our application.
For instance, let's say we are requesting data from an API server... when
developing this application, it's likely that we are going to be running a
development instance of the API server on our local machine (which would
be accessible through ).
Usually, we'll keep one file in the root to contain a global config that can
be overridden by configuration files on a per-environment basis.
263
It's usually a good idea to add to our file, so
we don't check in these settings.
Later, another developer (or us, months from now) can use the
file as a template for what the file should look like.
Let's navigate to the exploded directory where we'll see all of our
build tool written out for us. We won't look at all of these files, but to get an
understanding of what are doing, we'll start looking in
.
This file shows all of the webpack configuration used to build our app. It
includes loaders, plugins, entry points, etc. For our current task, the line to
look for is in the list where we define the :
264
The plugin takes an object with and and
finds all the places in our code where we use the key and it replaces it with
the value.
265
The result of the function would say "Hello from development".
To add our own variables to our app, we're going to use this object and
add our own definitions to it. Scrolling back up to the top of the file, we'll see
that it's currently created and exported from the file.
Looking at the file, we can see that it takes all the variables in
our environment and adds the to the environment as well as any
variables prefixed by .
266
267
We can skip all the complex part of that operation as we'll only need to
modify the second argument to the reduce function, in other words, we'll
update the object:
Let's get busy. In order to load the file, we'll need to import the
package. We'll also import the library from the standard node library
and set up a few variables for paths.
269
Next, let's concatenate all these variables together as well as include our
option in this object. The method creates a new
object and merges each object from right to left. This way, the environment
config variable
270
Now, anywhere in our code we can use the variables we set in our files.
Since we are making a request to an off-site server in our app, let's use our
new configuration options to update this host.
Now, for our production deployment, we'll use the heroku app, so let's create
a copy of the file as in the
directory:
Today was a long one, but tomorrow is an exciting day as we'll get the app up
and running on a remote server.
273
Great work today and see you tomorrow!
274
Deployment
Edit this page on Github (https://github.com/fullstackreact/30-days-of-react/blob/master/day-28/post.md)
We left off yesterday preparing for our first deployment of our application.
We're ready to deploy our application. Now the question is where and what
are we going to deploy?
Let's explore...
What
While deploying a single page application has it's own intricasies, it's similar
to deploying a non-single page application. What the end-user's browser
requests all need to be available for the browser to request. This means all
javascript files, any custom fonts, images, svg, stylesheets, etc. that we use in
our application need to be available on a publicly available server.
Webpack takes care of building and packaging our entire application for what
we'll need to give the server to send to our clients. This includes any client-
side tokens and our production configuration (which we put together
yesterday).
275
This means we only need to send the contents of the distribution directory
webpack put together. In our case, this directory is the directory. We
don't need to send anything else in our project to a remote server.
Let's use our build system to generate a list of production files we'll want to
host. We can run the command to generate these files in the
directory:
Where
These days we have many options for hosting client-side applications. We'll
look at a few options for hosting our application today. Each of the following
hosting services have their benefits and drawbacks, which we'll briefly
discuss before we actually make a deployment.
There are two possible ways for us to deploy our application. If we are
working with a back-end application, we can use the back-end server to host
our public application files. For instance, if we were building a rails
276
application, we can send the client-side application directly to the
folder of the rails application.
In this section, we'll work on hosting our client-side only application, which
is the second way we can deploy our application. This means we can run/use
a server which is specifically designed for hosting static files separate from
the back-end server.
We'll focus on the second method where we are using other services to
deploy our client-side application. That is, we'll skip building a back-end and
upload our static files to one (or more) of the (non-exhaustive) list of hosting
services.
surge.sh (https://surge.sh/)
github pages (https://pages.github.com/)
heroku (https://www.heroku.com/)
AWS S3 (https://aws.amazon.com/s3/)
Forge (https://getforge.com/)
BitBalloon (https://www.bitballoon.com/)
Pancake (https://www.pancake.io/)
... More
surge.sh
277
surge.sh (https://surge.sh/) is arguably one of the easiest hosting providers
to host our static site with. They provide a way for us to easily and repeatable
methods for hosting our sites.
Let's deploy our application to surge. First, we'll need to install the
command-line tool. We'll use , like so:
With the tool installed, we can run surge in our local directory and
point it to the directory to tell it to upload the generated files in the
directory.
The surge tool will run and it will upload all of our files to a domain specified
by the output of the tool. In the case of the previous run, this uploads our
files to the url of hateful-impulse.surge.sh (http://hateful-impulse.surge.sh/)
(or the SSL version at https://hateful-impulse.surge.sh/ (https://hateful-
impulse.surge.sh/))
278
For more information on , check out their documentation at
https://surge.sh/help/ (https://surge.sh/help/).
Github pages
279
github pages (https://pages.github.com/) is another easy service to deploy
our static files to. It's dependent upon using github to host our git files, but is
another easy-to-use hosting environment for single page applications.
We'll need to start by creating our github pages repository on github. With an
active account, we can visit the github.com/new (https://github.com/new)
site and create a repository.
With this repo, it will redirect us to the repo url. Let's click on the
button and find the github git url. Let's copy and paste this to our
clipboard and head to our terminal.
280
In our terminal, let's add this as a remote origin for our git repo.
Since we haven't created this as a git repo yet, let's initialize the git repo:
In the root directory of our application, let's add the remote with the
following command:
281
Since github pages does not serve directly from the root, but instead the
build folder, we'll need to add a configuration to our by setting
the key to the file with our github url. Let's open the
file and add the "homepage" key:
282
Hint
We can modify json files by using the jq (https://stedolan.github.io/jq/)
tool. If you don't have this installed, get it... get it now... It's invaluable
Now we can visit our site at the repo pages url. For instance, the demo site is:
https://auser.github.io/30-days-of-react-demo (https://auser.github.io/30-
days-of-react-demo/#).
283
Future deployments
We'll need to add this work to a deployment script, so every time we want
to release a new version of the site. We'll do more of this tomorrow. To
release to github, we'll have to use the following script:
Heroku
284
Heroku (https://www.heroku.com/) is a very cool hosting service that allows
us to host both static and non-static websites. We might want to deploy a
static site to heroku as we may want to move to a dynamic backend at some
point, are already comfortable with deploying to heroku, etc.
To deploy our site to heroku, we'll need an account. We can get one by
visiting https://signup.heroku.com/ (https://signup.heroku.com/) to sign up
for one.
Next, we'll need to tell the command-line that we have a heroku app.
We can do this by calling from the command-line in our
project root:
285
Heroku knows how to run our application thanks to buildpacks
(https://devcenter.heroku.com/articles/buildpacks). We'll need to tell
heroku we have a static-file buildpack so it knows to serve our application as
a static file/spa.
We'll need to install the static-files plugin for heroku. This can be easiy install
using the tool:
286
We can add the static file buildpack with the following command:
287
Now we can deploy our static site to heroku using the workflow:
We've deployed to only three of the hosting providers from the list above.
There are many more options for deploying our application, however this is a
pretty good start.
288
Continuous Integration
Edit this page on Github (https://github.com/fullstackreact/30-days-of-react/blob/master/day-29/post.md)
We've deployed our application to the "cloud", now we want to make sure
everything runs as we expect it. We've started a test suite, but now we want
to make sure it passes completely before we deploy.
Let's look at some better ways. One of the ways we can handle it is through a
deployment script that only succeeds if all of our tests pass. This is the
easiest, but needs to be replicated across a team of developers.
289
Another method is to push our code to a continuous integration server
whose only responsibility is to run our tests and deploy our application if and
only if the tests pass.
Just like hosting services, we have many options for running continuous
integration servers. The following is a short list of some of the popular CI
servers available:
travis ci (https://travis-ci.org/)
circle ci (https://circleci.com)
codeship (https://codeship.io)
jenkins (https://jenkins.io)
AWS EC2 (https://aws.amazon.com/ec2/)
Let's create a script that actually does do the deployment process first. In our
case, let's take the example from yesterday. Let's add one more
script we'll call in our directory:
In here, let's add the surge deploy script (changing the names to your domain
name, of course):
Let's write the release script next. To execute it, let's add the script to the
object:
290
Now let's create the file. From the root directory in our
terminal, let's execute the following command:
Inside this file, we'll want to run a few command-line scripts, first our
step, then we'll want to run our tests, and finally we'll run the deploy script, if
everything else succeeds first.
In a node file, we'll first set the to be for our build tooling.
We'll also include a script to run a command from the command-line from
within the node script and store all the output to an array.
291
When called, the function will return a promise that is resolved
when the command exits successfully and will reject if there is an error.
1. build
2. test
3. deploy
4. report any errors
Let's build these functions which will use our function we wrote
earlier:
292
With our file complete, let's execute our
command to make sure it deploys:
With all our tests passing, our updated application will be deployed
successfully!
293
If any of our tests fail, we'll get all the output of our command, including the
failure errors. Let's update one of our tests to make them fail purposefully to
test the script.
Let's rerun the script and watch it fail and not run the deploy script:
294
As we see, we'll get the output of the failing test in our logs, so we can fix the
bug and then rerelease our application again by running the
script again.
Travis CI
Travis ci (https://travis-ci.org/) is a hosted continuous integration
environment and is pretty easy to set up. Since we've pushed our container
to github, let's continue down this track and set up travis with our github
account.
295
Once you're signed up, click on the button and find your repository:
From the project screen, click on the big 'activate repo' button.
296
To allow Travis CI to automatically log in for us during deployment, we need
to add and environment variables. Open the More
Options menu and click settings.
Now we need to configure travis to do what we want, which is run our test
scripts and then deploy our app. To configure travis, we'll need to create a
file in the root of our app.
297
Let's add the following content to set the language to node with the node
version of 10.15.0:
Now all we need to do is add this file to git and push the repo
changes to github.
That's it. Now travis will execute our tests based on the default script of
.
Now, we'll want travis to actually deploy our app for us. Since we already have
a script that will deploy our app, we can use this to
deploy from travis.
298
To tell travis to run our script after we deploy, we will need to add
the key to our file. We also need to build our app before
deploy, hence the . Let's update the yml config to tell it to run
our deploy script:
The next time we push, travis will take over and push up to surge (or
wherever the scripts will tell it to deploy).
Other methods
There are a lot of other options we have to run our tests before we deploy.
This is just a getting started guide to get our application up.
299
The Travis CI service is fantastic for open-source projects,
however to use it in a private project, we'll need to create a
billable account.
Congrats! We have our application up and running, complete with testing and
all.
300
Wrap-up and More Resources
Edit this page on Github (https://github.com/fullstackreact/30-days-of-react/blob/master/day-30/post.md)
We've made it! Day 30. Congrats! Now you have enough
information to write some very complex applications, integrated
with data, styled to perfection, tested and deployed.
The final component of our trip through React-land is a call to get involved.
The React community is active, growing, and friendly.
We've covered a lot of material in the past 30 days. The high-level topics we
discussed in our first 30 days:
Interested in reading more and going deeper with React? Definitely check it
out. Not only do we cover in-depth the topics we briefly introduced in our
first 30 days, we go into a ton of other content, including (but not limited to):
302
303