How to Deploy Node Applications: Heroku vs

As Node.js continues to gain in popularity, new tutorials pop up teaching you to write server-side JavaScript apps and APIs. Once you’ve built your shiny new Node app, though, what then?
In this article, I’m going to take a look at a couple of options for deploying your Node applications. We’ll take a look at and Heroku.
I’ll explain how to deploy your code to each platform and we’ll end the article with a short summary of the pros and cons. I’ll pay attention to options for monitoring, ease of use, offered functionality and what the free hosting plan includes.
Deployment with Heroku
To be able to deploy apps to Heroku, you will have to sign up at Heroku and install the Heroku CLI for your machine. I prefer working from my terminal!
Before we can start, we need to add some code to the Procfile. Heroku makes use of this file to determine how to execute the uploaded code.
The following code needs to be added to the file so Heroku knows what command should be executed to start the app:
web: node app.js

Once this is done, try to log in from the terminal by typing heroku login. Heroku will ask you to enter your login credentials.
Next, navigate to the root of your project and enter the command: heroku create. This creates an app on Heroku which is ready to receive the source code of your project. The name of the app on Heroku is randomly created.
To deploy our code to Heroku, simply use git push heroku master. We can visit the app with the command heroku open which will open the generated URL.
Pushing changes to Heroku
Changes can be pushed by following the normal Github flow:
git add .
git commit -m “Changes made to app"
git push heroku master
heroku open

Useful Heroku Commands

To make sure that at least one instance of the app is running: heroku ps:scale web=1
Because we are using the free platform, it is not possible to upscale your application. However, it is possible to downscale so no instances of the application are running: heroku ps:scale web=0

View the latest logs (stream) in chronological order generated by Heroku: heroku logs –tail
It’s also possible to show the app logs only. App logs are the output of console.log() statements in your code and can be viewed with heroku logs –source app-name

Heroku provides the possibility to run your app locally at http://localhost:5000: heroku local web

List all Heroku apps: heroku apps

Remove a deployment: heroku apps:destroy –app app-name

Add owner (account) to access the app: heroku access:add, same for removing heroku access:remove

Heroku Environment Variables
If you are working with a .env file locally, you might want to use other environment variables for your Heroku deployment. It is possible to set these with heroku config:set PORT=3001. These values overwrite the variables set in you .env file.
To see all defined Heroku environment variables, just use heroku config. If you want to remove an environment variable for e.g. PORT, use heroku config:unset PORT.
Continue reading %How to Deploy Node Applications: Heroku vs


Quickly Create Simple yet Powerful Angular Forms

Forms are an essential part of many web applications, being the most common way to enter and edit text-based data. Front-end JavaScript frameworks such as Angular, often have their own idiomatic ways of creating and validating forms that you need to get to grips with to be productive.
Angular allows you to streamline this common task by providing two types of forms that you can create:

Template-driven forms – simple forms that can be made rather quickly.
Reactive forms – more complex forms that give you greater control over the elements in the form.

In this article, we’ll make a simple example form with each method to see how it’s done.
You do not need to know all the details of how to create an Angular application to understand the framework’s usefulness when it comes to forms. However, if you want to get a better grasp of Angular, you can take a look at this SitePoint article series on building a CRUD app with Angular.
We will use Bootstrap in this tutorial. It is not an integral part of an Angular application, but it will help us streamline our efforts even further by providing ready-made styles.
This is how you can add it to your application:

Open the command prompt and navigate to the folder of your project

Type npm install bootstrap@next. This will add the latest version of bootstrap to the project

Edit the .angular-cli.json file and add a link to the Bootstrap CSS file
“apps": [
"styles": [

We will not use the Bootstrap JavaScript file in this application.

Both template-driven Forms and Reactive Forms require the FormsModule. It should be added to the application in app.module:
import { FormsModule } from ‘@angular/forms’;
imports: [

With that out of the way, we can proceed with the forms themselves.
Template-Driven Forms
Let us assume you want to create a simple form as quickly as possible. For example, you need a company registration form. How can you create the form?
The first step is to create the

tag in your view.
<form #companyForm="ngForm">

We need to modify this tag in two ways in order to submit the form and use the information from the input fields in our component:

We will declare a template variable using the ngForm directive.
We will bind the ngSubmit event to a method we will create in our component

<form #companyForm="ngForm" (ngSubmit)="submitCompany(companyForm.form);">

We will create the submitCompany method in the component a bit later. It will be called when the form is submitted and we will pass it the data from the form via companyForm.form.
We also need a submit button, regardless of the content of the form. We will use a few Bootstrap classes to style the button. It is good practice to disable the button before all the data validation requirements are met. We can use the template variable we created for the form to achieve this. We will bind the disabled property to the valid property of the companyForm object. This way the button will be disabled if the form is not valid.
<button class="btn btn-primary" [disabled]="!companyForm.valid">Submit</button>

Let us assume our simple form will have two fields – an input field for the name of the company and a drop-down field for the company’s industry.
Creating form inputs
First, we create an input field for the name:
<input type="text"

Right now we have a standard input with the type, name and class attributes. What do we need to do to use the Angular approach on our input?
We need to apply the ngModel directive to it. Angular will create a control object and associate it with the field. Essentially, Angular does some of the work for you behind the scenes.
This is a good time to mention that ngModel requires the input field to have a name or the form control must be defined as standalone in ngModelOptions. This is not a problem because our form already has a name. Angular will use the name attribute to distinguish between the control objects.
In addition, we should specify a template variable for the input: #nameField in this case. Angular will set nameField to the ngModel directive that is applied to the input field. We will use this later for the input field’s validation. This variable will also allow us to perform an action based on the value of the field while we are typing in it.
Now our input looks like this:
<input type="text"

It is almost the same, but with a few key changes.
Let us assume we want the company name field to be required and to have a minimum length of 3 characters. This means we have to add the required and minlength attributes to our input:
<input type="text"

Sounds simple enough, right? We will also need to display an error message if any of these two requirements are not met. Angular allows us to check the input’s value and display the appropriate error message before the form is submitted.
We can perform such a check while the user is typing in the form. First of all, it is a good idea to display an error only after the user has started to interact with the form. There is no use in displaying an error message right after we load the page. This is why we will insert all the error messages for this input inside the following div:
<div *ngIf="nameField.touched && nameField.errors"></div>

The ngIf directive allows us to show the div only when a specific condition is true. We will use the nameField template variable again here because it is associated with the input. In our case, the div will be visible only, if the input has been touched and there is a problem with it. Alright, what about the error messages themselves?
We will place another div inside the aforementioned one for each error message we want. We will create a new div for the error message and use the nameField template variable again:
<div class="alert alert-danger"
The company name is required

We are using the "alert alert-danger" bootstrap classes to style the text field. The nameField variable has the property errors, which contains an object with key-value pairs for all the current errors. The ngIf directive allows us to show this error message only when the ‘required’ condition is not met. We will use the same approach for the error message about the minimum length.
Continue reading %Quickly Create Simple yet Powerful Angular Forms%


Ember.js: The Perfect Framework for Web Applications

Ember.js is an opinionated frontend JavaScript framework that has been getting a lot of interest lately. This article will introduce some key concepts of the framework while building a simple application with it, in order to show a basic example of what it is capable of producing.
Our example application is going to be a Dice Roller, including the ability to roll some dice and view a history of all dice rolls that have been performed to date. A fully working version of this application is available from Github
The Ember.js framework pulls together a lot of modern JavaScript concepts and technologies into one single bundle, including but not limited to:

The use of the Babel transpiler tool, to support ES2016 throughout.
Testing support at the Unit, Integration and Acceptance levels as standard, powered by Testem and QTest.
Asset building using Broccoli.js.
Support for live reloading, for shorter development cycle times.
Templating using the Handlebars markup syntax.
URL Routing first development to ensure that deep linking is fully supported throughout.
Full data layer built around JSON API, but pluggable for whatever API access you need.

In order to work with Ember.js, it is assumed that you have an up-to-date installation of Node.js and npm. If not then these can be downloaded and installed from the Node.js website.
It should also be mentioned that Ember is purely a frontend framework. It has a number of ways of interacting with the backend of your choice, but this backend is not in any way handled by Ember itself.
Introducing ember-cli
A lot of the power of Ember.js comes from its command line interface (CLI). This tool – known as ember-cli – powers much of the development lifecycle of an Ember.js application, starting from creating the application, through adding functionality into it all the way to running the test suites and starting the actual project in development mode.
Almost everything that you do whilst developing an Ember.js application will involve this tool at some level, so it is important to understand how best to use it. We will be making use of it throughout this article.
The first thing we need to do is ensure that the Ember.js CLI is correctly installed and up-to-date. This is done by installing from npm, as follows:
$ npm install -g ember-cli

and we can check it was successfully installed by running the following command:
$ ember –version
ember-cli: 2.15.0-beta.1
node: 8.2.1
os: darwin x64

Creating Your First Ember.js App
Once ember-cli is installed, you are ready to start creating your application. This is the first place we will be making use of the Ember.js CLI tool – it creates the entire application structure, setting everything up ready to run.
$ ember new dice-roller
installing app
create .editorconfig
create .ember-cli
create .eslintrc.js
create .travis.yml
create .watchmanconfig
create app/app.js
create app/components/.gitkeep
create app/controllers/.gitkeep
create app/helpers/.gitkeep
create app/index.html
create app/models/.gitkeep
create app/resolver.js
create app/router.js
create app/routes/.gitkeep
create app/styles/app.css
create app/templates/application.hbs
create app/templates/components/.gitkeep
create config/environment.js
create config/targets.js
create ember-cli-build.js
create .gitignore
create package.json
create public/crossdomain.xml
create public/robots.txt
create testem.js
create tests/.eslintrc.js
create tests/helpers/destroy-app.js
create tests/helpers/module-for-acceptance.js
create tests/helpers/resolver.js
create tests/helpers/start-app.js
create tests/index.html
create tests/integration/.gitkeep
create tests/test-helper.js
create tests/unit/.gitkeep
create vendor/.gitkeep
NPM: Installed dependencies
Successfully initialized git.


This has caused an entire application to be created which is ready to run. It has even set up Git as source control to track your work.

Note: If you wish, you can disable the Git integration and you can prefer Yarn over npm. The help for the tool describes this and much more.

Now, let’s see what it looks like. Starting the Ember application for development purposes is – once again – also done using ember-cli:
$ cd dice-roller
$ ember serve
Livereload server on http://localhost:49153
‘instrument’ is imported from external module ’ember-data/-debug’ but never used
Warning: ignoring input sourcemap for vendor/ember/ember.debug.js because ENOENT: no such file or directory, open ‘/Users/coxg/source/me/writing/repos/dice-roller/tmp/source_map_concat-input_base_path-2fXNPqjl.tmp/vendor/ember/’
Warning: ignoring input sourcemap for vendor/ember/ember-testing.js because ENOENT: no such file or directory, open ‘/Users/coxg/source/me/writing/repos/dice-roller/tmp/source_map_concat-input_base_path-Xwpjztar.tmp/vendor/ember/’

Build successful (5835ms) – Serving on http://localhost:4200/

Slowest Nodes (totalTime => 5% ) | Total (avg)
Babel (16) | 4625ms (289 ms)
Rollup (1) | 445ms

We are now ready to go. The application is running on http://localhost:4200, and looks like this:

It is also running a LiveReload service which automatically watches for changes to the filesystem. This means that you can have an incredibly fast turnaround time when tweaking your site design.
Let’s try it?
The initial page already tells us what to do, so let’s go and change the main page and see what happens. We’re going to change the app/templates/application.hbs file to look like the following.
This is my new application.

Note: The tag is part of how Routing works in Ember. We will cover that later on.

The first thing to notice is the output from ember-cli, which should look as follows:
file changed templates/application.hbs

Build successful (67ms) – Serving on http://localhost:4200/

Slowest Nodes (totalTime => 5% ) | Total (avg)
SourceMapConcat: Concat: App (1) | 9ms
SourceMapConcat: Concat: Vendor /asset… (1) | 8ms
SimpleConcatConcat: Concat: Vendor Sty… (1) | 4ms
Funnel (7) | 4ms (0 ms)

This tells us that it has spotted that we changed the template and rebuilt and restarted everything. We’ve had zero involvement in that part of it.
Now let’s look at the browser. If you’ve got LiveReload installed and running you will not even have needed to refresh the browser for this to be picked up, otherwise, you will need to reload the current page.

Not very exciting, but this is with almost no effort on our part that we’ve achieved this.
In addition, we get a fully set up test suite ready to run. This is – unsurprisingly – run using the Ember tool as well, as follows:
$ ember test
⠸ Building’instrument’ is imported from external module ’ember-data/-debug’ but never used
⠴ BuildingWarning: ignoring input sourcemap for vendor/ember/ember.debug.js because ENOENT: no such file or directory, open ‘/Users/coxg/source/me/writing/repos/dice-roller/tmp/source_map_concat-input_base_path-S8aQFGaz.tmp/vendor/ember/’
⠇ BuildingWarning: ignoring input sourcemap for vendor/ember/ember-testing.js because ENOENT: no such file or directory, open ‘/Users/coxg/source/me/writing/repos/dice-roller/tmp/source_map_concat-input_base_path-wO8OLEE2.tmp/vendor/ember/’
cleaning up…
Built project successfully. Stored in “/Users/coxg/source/me/writing/repos/dice-roller/tmp/class-tests_dist-PUnMT5zL.tmp".
ok 1 PhantomJS 2.1 – ESLint | app: app.js
ok 2 PhantomJS 2.1 – ESLint | app: resolver.js
ok 3 PhantomJS 2.1 – ESLint | app: router.js
ok 4 PhantomJS 2.1 – ESLint | tests: helpers/destroy-app.js
ok 5 PhantomJS 2.1 – ESLint | tests: helpers/module-for-acceptance.js
ok 6 PhantomJS 2.1 – ESLint | tests: helpers/resolver.js
ok 7 PhantomJS 2.1 – ESLint | tests: helpers/start-app.js
ok 8 PhantomJS 2.1 – ESLint | tests: test-helper.js

# tests 8
# pass 8
# skip 0
# fail 0

# ok

Note that the output talks about PhantomJS. This is because there is full support for Integration tests that run in a browser, and by default, these run headless in the PhantomJS browser. There is full support for running them in other browsers if you wish, and when setting up continuous integration (CI) it is worth doing this to ensure that your application works correctly in all supported browsers.
How an Ember.js app is structured
Before we get to actually writing our application, let’s explore how it is structured on the filesystem. The ember new command above will have created a whole directory structure on your computer, with lots of different parts. Understanding all of these is important to efficiently work with the tool and create amazing projects.
Continue reading %Ember.js: The Perfect Framework for Web Applications%


React Lifecycle Reference Guide

This is a reference guide to help developers quickly figure out which lifecycle method will best fit a solution they’re currently working on in React.
The constructor for a React component is the first method that gets called. This is where you should initiate state. You should ensure you execute super(props) first. Otherwise, bugs will crop up.
constructor(props) {
this.state = {
count: props.initialCount

This method is called just before component mounting and render method. Setting state here won’t trigger a re-render. This method sounds like a nice place to set the component’s initial state. However, React’s official guidelines recommend using the constructor() instead.
componentWillMount() {
// perform setState operations

This is a mandatory method for all React components. It will be invoked when state changes, when the parent component causes it to re-render, or when component.forceUpdate() is called.
The render() method is where you put your JSX code. You can also return false or null if you don’t want to render anything. You can read values from this.prop and this.state, but you can’t call this.setState() (or call another function that does). You should also not directly interact with the DOM. Instead, use componentDidMount().
render() {
const {message} = this.state;


h1>List of Messages</h1>
<MessageView message={message} />

This method is invoked right after the component has been mounted and render() has been called. Once a component mounts, it means you have access to the actual DOM nodes. This is a good place for performing network requests such as an API call. If you set state here, a re-render will be triggered.
componentDidMount = () => {

shouldComponentUpdate(nextProps, nextState)
This method is invoked just before render() whenever there are new props or state changes. The method should only return true or false. If you return false, this means the render function won’t be called. However, do note that:

this method isn’t called in the initial rendering
child components will still re-render if you return false
future versions may not enforce this directive, but instead use it as a hint.

This method has access to nextProps and nextState, which gives you an opportunity to compare them with the current props/state and determine if a re-render is necessary. This is a good place to implement performance optimization code.
shouldComponentUpdate(nextProps, nextState) {
// put performance optimization code here
return true;

Continue reading %React Lifecycle Reference Guide%


An Introduction to JSX

When React was first introduced, one of the features that caught most people’s attention (and drew the most criticism) was JSX. If you’re learning React, or have ever seen any code examples, you probably did a double-take at the syntax. What is this strange amalgamation of HTML and JavaScript? Is this even real code?
Let’s take a look at what JSX actually is, how it works, and why the heck we’d want to be mixing HTML and JS in the first place!
What is JSX?
Defined by the React Docs as an “extension to JavaScript" or “syntax sugar for calling React.createElement(component, props, …children))”, JSX is what makes writing your React Components easy.
JSX is considered a domain-specific language (DSL), which can look very similar to a template language, such as Mustache, Thymeleaf, Razor, Twig, or others.
It doesn’t render out to HTML directly, but instead renders to React Classes that are consumed by the Virtual DOM. Eventually, through the mysterious magic of the Virtual DOM, it will make its way to the page and be rendered out to HTML.
How Does it Work?
JSX is basically still just JavaScript with some extra functionality. With JSX, you can write code that looks very similar to HTML or XML, but you have the power of seamlessly mixing JavaScript methods and variables into your code. JSX is interpreted by a transpiler, such as Babel, and rendered to JavaScript code that the UI Framework (React, in this case) can understand.
Don’t like JSX? That’s cool. It’s technically not required, and the React Docs actually include a section on using “React Without JSX”. Let me warn you right now, though, it’s not pretty. Don’t believe me? Take a look.
class SitePoint extends Component {
render() {
return (

My name is <span>{this.props.myName}</span></div>

React Sans JSX:
class SitePoint extends Component {
render() {
return React.createElement(
"My name is",

Sure, looking at those small example pieces of code on that page you might be thinking, "Oh, that’s not so bad, I could do that." But could you imagine writing an entire application like that?
The example is just two simple nested HTML elements, nothing fancy. Basically, just a nested Hello World. Trying to write your React application without JSX would be extremely time consuming and, if you’re like most of us other developers out here working as characters in DevLand™, it will very likely quickly turn into a convoluted spaghetti code mess. Yuck!
Using frameworks and libraries and things like that are meant to make our lives easier, not harder. I’m sure we’ve all seen the overuse and abuse of libraries or frameworks in our careers, but using JSX with your React is definitely not one of those cases.
Continue reading %An Introduction to JSX%


Using Preact as a React Alternative

Preact is an implementation of the virtual DOM component paradigm just like React and many other similar libraries. Unlike React, it’s only 3KB in size, and it also outperforms it in terms of speed. It’s created by Jason Miller and available under the well-known permissive and open-source MIT license.
Why Use Preact?
Preact is a lightweight version of React. You may prefer to use Preact as a lightweight alternative if you like building views with React but performance, speed and size are a priority for you — for example, in case of mobile web apps or progressive web apps.
Whether you’re starting a new project or developing an existing one, Preact can save you a lot of time. You don’t need to reinvent the wheel trying to learn a new library, since it’s similar to, and compatible with, React — to the point that you can use existing React packages with it with only some aliasing, thanks to the compatibility layer preact-compat.
Pros and Cons
There are many differences between React and Preact that we can summarize in three points:

Features and API: Preact includes only a subset of the React API, and not all available features in React.
Size: Preact is much smaller than React.
Performance: Preact is faster than React.

Every library out there has its own set of pros and cons, and only your priorities can help you decide which library is a good fit for your next project. In this section, I’ll try to list the pros and cons of the two libraries.
Preact Pros

Preact is lightweight, smaller (only 3KB in size when gzipped) and faster than React (see these tests). You can also run performance tests in your browser via this link.
Preact is largely compatible with React, and has the same ES6 API as React, which makes it dead easy either to adopt Preact as a new library for building user interfaces in your project or to swap React with Preact for an existing project for performance reasons.
It has good documentation and examples available from the official website.
It has a powerful and official CLI for quickly creating new Preact projects, without the hassle of Webpack and Babel configuration.
Many features are inspired by all the work already done on React.
It has also its own set of advanced features independent from React, like Linked State.

React Pros

React supports one-way data binding.
It’s backed by a large company, Facebook.
Good documentation, examples, and tutorials on the official website and the web.
Large community.
Used on Facebook’s website, which has millions of visitors worldwide.
Has its own official developer debugging tools extension for Chrome.
It has the Create React App project boilerplate for quickly creating projects with zero configuration.
It has a well-architectured and complex codebase.

React Cons

React has a relatively large size in comparison with Preact or other existing similar libraries. (React minified source file is around 136KB in size, or about 42KB when minified and gzipped.)
It’s slower than Preact.
As a result of its complex codebase, it’s harder for novice developers to contribute.

Note: Another con I listed while writing this article was that React had a grant patent clause paired with the BSD license, making it legally unsuitable for some use cases. However, in September 2017, the React license switched MIT, which resolved these license concerns.
Preact Cons

Preact supports only stateless functional components and ES6 class-based component definition, so there’s no createClass.
No support for context.
No support for React propTypes.
Smaller community than React.

Getting Started with Preact CLI
Preact CLI is a command line tool created by Preact’s author, Jason Miller. It makes it very easy to create a new Preact project without getting bogged down with configuration complexities, so let’s start by installing it.
Open your terminal (Linux or macOS) or command prompt (Windows), then run the following commands:
npm i -g preact-cli@latest

This will install the latest version of Preact CLI, assuming you have Node and NPM installed on your local development machine.
You can now create your project with this:
preact create my-app

Or with this, ff you want to create your app interactively:
preact init

Next, navigate inside your app’s root folder and run this:
npm start

This will start a live-reload development server.
Finally, when you finish developing your app, you can build a production release using this:
npm run build

Continue reading %Using Preact as a React Alternative%


Extracting Website Data and Creating APIs with WrapAPI

Today, almost all services we use have some sort of API. Some web applications are even built from API points alone, being passed to some kind of front-end view. If you’re a consumer of a service that provides an API, you’ll sometimes need more features or find limits to what the API can offer. In this article, we’ll cover a service that’s useful both for API consumers and creators.
I always go with the saying that, if there’s a web interface, you can build your own API over it. WrapAPI tries to make this process easier. If you’re familiar with the process of web scraping/crawling (or extracting data from websites), you’ll see the magic of WrapAPI.
WrapAPI offers a service that allows you to easily extract information from websites and create APIs from the data. It provides an easy, interactive way of selecting what information you want to get. With just a few clicks, you can have your API online.
To follow along with this tutorial, I recommend you head over to and create an account.
How To Get Around WrapAPI
On the WrapAPI site, you’ll see that you can start to build your project right away — although, unless you create an account, your work won’t be saved.
Once you’ve signed up, click the Try building an API button.

You’ll be presented by a browser-like interface. On top of the site we’re presented with a URL bar. As an example, WrapAPI uses Hacker News ( If you click the URL to change it to something else, you’ll see more options related to the request you want to make. We’ll use the default options, and only change the URL to We’re covering only the GET method, as we only want to get data in this example.
Below the URL bar there are four buttons that give you different information regarding the site you’re viewing. Browser view displays the site as you would visit it from your browser. Code view displays the source code of the site. Headers shows the response you get from the server. This is useful if you want to see what response you get from the server: it gives you information like the HTTP status codes (200, 404, 400 etc.), content types, web servers and so on. You can also view the request’s Cookies directly from the builder.
Getting the Data
By now you should be able to see SitePoint inside the Browser View frame.

Let’s create a very simple API that shows us the latest post titles of the JavaScript channel. If you hover over the titles, images or any other element in the site, you’ll notice a selection color covering it. Let’s scroll down a bit, to the LATEST articles part. Hover over the title from one of the articles and click on that title. You’ll notice that it doesn’t switch to that particular link we clicked. We see that every title in this section is highlighted. WrapAPI guessed that these are all the titles we want. Sometimes it can also select parts of the sites we don’t want. That’s usually the case when the CSS class selectors are not well-defined or used by other elements in the site.
Besides CSS selectors, WrapAPI supports regular expressions, JSON selectors, headers, cookies, form outputs, and a bunch more options. You can use them all together and extract exactly what you’re aiming for. In this example, we’ll only use CSS selectors.

In the right part of the interface, you’ll see three tabs. Let’s take a look at the current Build tab. Outputs will show us the selectors (in our case CSS selectors), and you’ll get more details on what you would like to select. We’re interested only in extracting the title, which is text. There are more options on cleaning the result output, but we won’t get into these details. If you’d like to create another selector, to select description, author, date, etc., just click the Create a new collection/output. Naming your selectors is also important, as this will make it easier if you use multiple selectors in the site. By clicking the pencil icon, you can edit your selectors.

The Preview tab will show a representation of our data in JSON, and you probably get the idea of what the API will look like. If you’re happy with the results, you can click the Save button to save a version of the API.

You’ll need to enter the repository and the endpoint name of the API. It helps you manage and organize your APIs. That will also be part of your API’s name in the end. After entering the information, you’ll return to the builder. Our API is saved, but now we need to test and publish it.

If the site has pagination (previous/next pages), you can use the query string options. (More on that here.)
Name your selectors correctly, as they’ll be part of the JSON output.

Continue reading %Extracting Website Data and Creating APIs with WrapAPI%


Conditionally Applying a CSS Class in Vue.js

There are times you need to change an element’s CSS classes at runtime. But when changing classes, it’s sometimes best to apply style details conditionally. For example, imagine your view has a pager. Pagers are often used to navigate larger sets of items. When navigating, it can be helpful to show the user the page they’re currently on. The style of the item is conditionally set, based on the current page that’s being viewed.
A pager in this case may look something like this:

In this example, there are five pages. Only one of these pages is selected at a time. If you built this pager with Bootstrap, the selected page would have a CSS class named active applied. You’d want this class applied only if the page was the currently viewed page. In other words, you’d want to conditionally apply the active CSS class. As discussed in my Vue.js tutorial, Vue provides a way to conditionally apply a CSS class to an element. I’m going to show you this technique in this article.
To conditionally apply a CSS class at runtime, you can bind to a JavaScript object. To successfully complete this task, you must complete two steps. First, you must ensure that your CSS class is defined. Then, you create the class bindings in your template. I’m going to explain each of these steps in detail in the rest of this article.
Step 1: Define Your CSS Classes
Imagine, for a moment, that the five page items shown in the image above were defined using the following HTML:

React Router v4: The Complete Guide

React Router is the de facto standard routing library for React. When you need to navigate through a React application with multiple views, you’ll need a router to manage the URLs. React Router takes care of that, keeping your application UI and the URL in sync.
This tutorial introduces you to React Router v4 and a whole lot of things you can do with it.
React is a popular library for creating single-page applications (SPAs) that are rendered on the client side. An SPA might have multiple views (aka pages), and unlike the conventional multi-page apps, navigating through these views shouldn’t result in the entire page being reloaded. Instead, we want the views to be rendered inline within the current page. The end user, who’s accustomed to multi-page apps, expects the following features to be present in an SPA:

Each view in an application should have a URL that uniquely specifies that view. This is so that the user can bookmark the URL for reference at a later time — e.g.
The browser’s back and forward button should work as expected.
The dynamically generated nested views should preferably have a URL of their own too — e.g., where 101 is the product id.

Routing is the process of keeping the browser URL in sync with what’s being rendered on the page. React Router lets you handle routing declaratively. The declarative routing approach allows you to control the data flow in your application, by saying “the route should look like this":

You can place your <Route> component anywhere that you want your route to be rendered. Since <Route>, <Link> and all the other React Router API that we’ll be dealing with are just components, you can easily get used to routing in React.
A note before getting started. There’s a common misconception that React Router is an official routing solution developed by Facebook. In reality, it’s a third-party library that’s widely popular for its design and simplicity. If your requirements are limited to routers for navigation, you could implement a custom router from scratch without much hassle. However, understanding how the basics of React Router will give you better insights into how a router should work.
This tutorial is divided into different sections. First, we’ll be setting up React and React Router using npm. Then we’ll jump right into React Router basics. You’ll find different code demonstrations of React Router in action. The examples covered in this tutorial include:

basic navigational routing
nested routing
nested routing with path parameters
protected routing

All the concepts connected with building these routes will be discussed along the way. The entire code for the project is available on this GitHub repo. Once you’re inside a particular demo directory, run npm install to install the dependencies. To serve the application on a development server, run npm start and head over to http://localhost:3000/ to see the demo in action.
Let’s get started!
Setting up React Router
I assume you already have a development environment up and running. If not, head over to “Getting Started with React and JSX”. Alternatively, you can use Create React App to generate the files required for creating a basic React project. This is the default directory structure generated by Create React App:
├── .gitignore
├── package.json
├── public
│ ├── favicon.ico
│ ├── index.html
│ └── manifest.json
├── src
│ ├── App.css
│ ├── App.js
│ ├── App.test.js
│ ├── index.css
│ ├── index.js
│ ├── logo.svg
│ └── registerServiceWorker.js
└── yarn.lock

The React Router library comprises three packages: react-router, react-router-dom, and react-router-native. react-router is the core package for the router, whereas the other two are environment specific. You should use react-router-dom if you’re building a website, and react-router-native if you’re on a mobile app development environment using React Native.
Use npm to install react-router-dom:
npm install –save react-router-dom

React Router Basics
Here’s an example of how our routes will look:
<Route exact path="/" component={Home}/>
<Route path="/category" component={Category}/>
<Route path="/login" component={Login}/>
<Route path="/products" component={Products}/>

You need a router component and several route components to set up a basic route as exemplified above. Since we’re building a browser-based application, we can use two types of routers from the React Router API:


The primary difference between them is evident in the URLs that they create:
// <BrowserRouter>

// <HashRouter>

The <BrowserRouter> is more popular amongst the two because it uses the HTML5 History API to keep track of your router history. The <HashRouter>, on the other hand, uses the hash portion of the URL (window.location.hash) to remember things. If you intend to support legacy browsers, you should stick with <HashRouter>.
Wrap the <BrowserRouter> component around the App component.
/* Import statements */
import React from ‘react’;
import ReactDOM from ‘react-dom’;

/* App is the entry point to the React code.*/
import App from ‘./App’;

/* import BrowserRouter from ‘react-router-dom’ */
import { BrowserRouter } from ‘react-router-dom’;

<App />
, document.getElementById(‘root’));

Note: A router component can only have a single child element. The child element can be an HTML element — such as div — or a react component.
For the React Router to work, you need to import the relevant API from the react-router-dom library. Here I’ve imported the BrowserRouter into index.js. I’ve also imported the App component from App.js. App.js, as you might have guessed, is the entry point to React components.
The above code creates an instance of history for our entire App component. Let me formally introduce you to history.

history is a JavaScript library that lets you easily manage session history anywhere JavaScript runs. history provides a minimal API that lets you manage the history stack, navigate, confirm navigation, and persist state between sessions. — React Training docs

Each router component creates a history object that keeps track of the current location (history.location) and also the previous locations in a stack. When the current location changes, the view is re-rendered and you get a sense of navigation. How does the current location change? The history object has methods such as history.push() and history.replace() to take care of that. history.push() is invoked when you click on a <Link> component, and history.replace() is called when you use <Redirect>. Other methods — such as history.goBack() and history.goForward() — are used to navigate through the history stack by going back or forward a page.
Moving on, we have Links and Routes.
Links and Routes
The <Route> component is the most important component in React router. It renders some UI if the current location matches the route’s path. Ideally, a <Route> component should have a prop named path, and if the pathname is matched with the current location, it gets rendered.
The <Link> component, on the other hand, is used to navigate between pages. It’s comparable to the HTML anchor element. However, using anchor links would result in a browser refresh, which we don’t want. So instead, we can use <Link> to navigate to a particular URL and have the view re-rendered without a browser refresh.
We’ve covered everything you need to know to create a basic router. Let’s build one.
Demo 1: Basic Routing
/* Import statements */
import React, { Component } from ‘react’;
import { Link, Route, Switch } from ‘react-router-dom’;

/* Home component */
const Home = () => (

/* Category component */
const Category = () => (

/* Products component */
const Products = () => (

/* App component */
class App extends React.Component {
render() {
return (
<nav className="navbar navbar-light">
<ul className="nav navbar-nav">

/* Link components are used for linking to other views */
<li><Link to="/">Homes</Link></li>
<li><Link to="/category">Category</Link></li>
<li><Link to="/products">Products</Link></li>


/* Route components are rendered if the path prop matches the current URL */
<Route path="/" component={Home}/>
<Route path="/category" component={Category}/>
<Route path="/products" component={Products}/>


We’ve declared the components for Home, Category and Products inside App.js. Although this is okay for now, when the component starts to grow bigger, it’s better to have a separate file for each component. As a rule of thumb, I usually create a new file for a component if it occupies more than 10 lines of code. Starting from the second demo, I’ll be creating a separate file for components that have grown too big to fit inside the App.js file.
Inside the App component, we’ve written the logic for routing. The <Route>’s path is matched with the current location and a component gets rendered. The component that should be rendered is passed in as a second prop.
Here / matches both / and /category. Therefore, both the routes are matched and rendered. How do we avoid that? You should pass the exact= {true} props to the router with path=’/’:
<Route exact={true} path="/" component={Home}/>

If you want a route to be rendered only if the paths are exactly the same, you should use the exact props.
Nested Routing
To create nested routes, we need to have a better understanding of how <Route> works. Let’s do that.
<Route> has three props that you can you use to define what gets rendered:

component. We’ve already seen this in action. When the URL is matched, the router creates a React element from the given component using React.createElement.
render. This is handy for inline rendering. The render prop expects a function that returns an element when the location matches the route’s path.
children. The children prop is similar to render in that it expects a function that returns a React element. However, children gets rendered regardless of whether the path is matched with the location or not.

Path and match
The path is used to identify the portion of the URL that the router should match. It uses the Path-to-RegExp library to turn a path string into a regular expression. It will then be matched against the current location.
If the router’s path and the location are successfully matched, an object is created and we call it the match object. The match object carries more information about the URL and the path. This information is accessible through its properties, listed below:

match.url. A string that returns the matched portion of the URL. This is particularly useful for building nested <Link>s
match.path. A string that returns the route’s path string — that is, <Route path="">. We’ll be using this to build nested <Route>s.
match.isExact. A boolean that returns true if the match was exact (without any trailing characters).
match.params. An object containing key/value pairs from the URL parsed by the Path-to-RegExp package.

Now that we know all about <Route>s, let’s build a router with nested routes.
Switch Component
Before we head for the demo code, I want to introduce you to the <Switch> component. When multiple <Route>s are used together, all the routes that match are rendered inclusively. Consider this code from demo 1. I’ve added a new route to demonstrate why <Switch> is useful.
<Route exact path="/" component={Home}/>
<Route path="/products" component={Products}/>
<Route path="/category" component={Category}/>
<Route path="/:id" render = {()=> (<p> I want this text to show up for all routes other than ‘/’, ‘/products’ and ‘/category’ </p>)}/>

If the URL is /products, all the routes that match the location /products are rendered. So, the <Route> with path :id gets rendered along with the Products component. This is by design. However, if this is not the behavior you’re expecting, you should add the <Switch> component to your routes. With <Switch>, only the first child <Route> that matches the location gets rendered.
Continue reading %React Router v4: The Complete Guide%


Getting Started with Redux

A typical web application is usually composed of several UI components that share data. Often, multiple components are tasked with the responsibility of displaying different properties of the same object. This object represents state which can change at any time. Keeping state consistent among multiple components can be a nightmare, especially if there are multiple channels being used to update the same object.
Take, for example, a site with a shopping cart. At the top we have a UI component showing the number of items in the cart. We could also have another UI component that displays the total cost of items in the cart. If a user clicks the Add to Cart button, both of these components should update immediately with the correct figures. If the user decides to remove an item from the cart, change quantity, add a protection plan, use a coupon or change shipping location, then the relevant UI components should update to display the correct information. As you can see, a simple shopping cart can quickly become difficult to keep in sync as the scope of its features grows.
In this guide, I’ll introduce you to a framework known as Redux, which can help you build complex projects in way that’s easy to scale and maintain. To make learning easier, we’ll use a simplified shopping cart project to learn how Redux works. You’ll need to be at least familiar with the React library, as you’ll later need to integrate it with Redux.
Before we get started, make sure you’re familiar with the following topics:

Functional JavaScript
Object-oriented JavaScript
ES6 JavaScript Syntax

Also, ensure you have the following setup on your machine:

a NodeJS environment
a Yarn setup (recommended)

You can access the entire code used in this tutorial on GitHub.
What is Redux
Redux is a popular JavaScript framework that provides a predictable state container for applications. Redux is based on a simplified version of Flux, a framework developed by Facebook. Unlike standard MVC frameworks, where data can flow between UI components and storage in both directions, Redux strictly allows data to flow in one direction only. See the below illustration:

Figure 1: Redux Flow Chart

In Redux, all data — i.e. state — is held in a container known as the store. There can only be one of these within an application. The store is essentially a state tree where states for all objects are kept. Any UI component can access the state of a particular object directly from the store. To change a state from a local or remote component, an action needs to be dispatched. Dispatch in this context means sending actionable information to the store. When a store receives an action, it delegates it to the relevant reducer. A reducer is simply a pure function that looks at the previous state, performs an action and returns a new state. To see all this in action, we need to start coding.
Understand Immutability First
Before we start, I need you to first understand what immutability means in JavaScript. According to the Oxford English Dictionary, immutability means being unchangeable. In programming, we write code that changes the values of variables all the time. This is referred to as mutability. The way we do this can often cause unexpected bugs in our projects. If your code only deals with primitive data types (numbers, strings, booleans), then you don’t need to worry. However, if you’re working with Arrays and Objects, performing mutable operations on them can create unexpected bugs. To demonstrate this, open your terminal and launch the Node interactive shell:

Next, let’s create an array, then later assign it to another variable:
> let a = [1,2,3]
> let b = a
> b.push(9)
> console.log(b)
[ 1, 2, 3, 9 ] // b output
> console.log(a)
[ 1, 2, 3, 9 ] // a output

As you can see, updating array b caused array a to change as well. This happens because Objects and Arrays are known referential data types — meaning that such data types don’t actually hold values themselves, but are pointers to a memory location where the values are stored. By assigning a to b, we merely created a second pointer that references the same location. To fix this, we need to copy the referenced values to a new location. In JavaScript, there are three different ways of achieving this:

using immutable data structures created by Immutable.js
using JavaScript libraries such as Underscore and Lodash to execute immutable operations
using native ES6 functions to execute immutable operations.

For this article, we’ll use the ES6 way, since it’s already available in the NodeJS environment. Inside your NodeJS terminal, execute the following:
> a = [1,2,3] // reset a
[ 1, 2, 3 ]
> b = Object.assign([],a) // copy array a to b
[ 1, 2, 3 ]
> b.push(8)
> console.log(b)
[ 1, 2, 3, 8 ] // b output
> console.log(a)
[ 1, 2, 3 ] // a output

In the above code example, array b can now be modified without affecting array a. We’ve used Object.assign() to create a new copy of values that variable b will now point to. We can also use the rest operator(…) to perform an immutable operation like this:
> a = [1,2,3]
[ 1, 2, 3 ]
> b = […a, 4, 5, 6]
[ 1, 2, 3, 4, 5, 6 ]
> a
[ 1, 2, 3 ]

The rest operator works with object literals too! I won’t go deep into this subject, but here are some additional ES6 functions that we’ll use to perform immutable operations:

spread syntax — useful in append operations
map function — useful in an update operation
filter function — useful in a delete operation

In case the documentation I’ve linked isn’t useful, don’t worry, as you’ll see how they’re used in practice. Let’s start coding!
Setting up Redux
The fastest way to set up a Redux development environment is to use the create-react-app tool. Before we begin, make sure you’ve installed and updated nodejs, npm and yarn. Let’s set up a Redux project by generating a redux-shopping-cart project and installing the Redux package:
create-react-app redux-shopping-cart

cd redux-shopping-cart
yarn add redux # or npm install redux

Delete all files inside the src folder except index.js. Open the file and clear out all existing code. Type the following:
import { createStore } from “redux";

const reducer = function(state, action) {
return state;

const store = createStore(reducer);

Let me explain what the above piece of code does:

1st statement. We import a createStore() function from the Redux package.
2nd statement. We create an empty function known as a reducer. The first argument, state, is current data held in the store. The second argument, action, is a container for:

type — a simple string constant e.g. ADD, UPDATE, DELETE etc.
payload — data for updating state

3rd statement. We create a Redux store, which can only be constructed using a reducer as a parameter. The data kept in the Redux store can be accessed directly, but can only be updated via the supplied reducer.

You may have noticed I mentioned current data as if it already exists. Currently, our state is undefined or null. To remedy this, just assign a default value to state like this to make it an empty array:
const reducer = function(state=[], action) {
return state;

Now, let’s get practical. The reducer we created is generic. Its name doesn’t describe what it’s for. Then there’s the issue of how we work with multiple reducers. The answer is to use a combineReducers function that’s supplied by the Redux package. Update your code as follows:
// src/index.js

import { combineReducers } from ‘redux’;

const productsReducer = function(state=[], action) {
return state;

const cartReducer = function(state=[], action) {
return state;

const allReducers = {
products: productsReducer,
shoppingCart: cartReducer

const rootReducer = combineReducers(allReducers);

let store = createStore(rootReducer);

In the code above, we’ve renamed the generic reducer to cartReducer. There’s also a new empty reducer named productsReducer that I’ve created just to show you how to combine multiple reducers within a single store using the combineReducers function.
Next, we’ll look at how we can define some test data for our reducers. Update the code as follows:
// src/index.js

const initialState = {
cart: [
product: ‘bread 700g’,
quantity: 2,
unitCost: 90
product: ‘milk 500ml’,
quantity: 1,
unitCost: 47

const cartReducer = function(state=initialState, action) {
return state;

let store = createStore(rootReducer);

console.log("initial state: ", store.getState());

Just to confirm that the store has some initial data, we use store.getState() to print out the current state in the console. You can run the dev server by executing npm start or yarn start in the console. Then press Ctrl+Shift+I to open the inspector tab in Chrome in order to view the console tab.

Figure 2: Redux Initial State

Currently, our cartReducer does nothing, yet it’s supposed to manage the state of our shopping cart items within the Redux store. We need to define actions for adding, updating and deleting shopping cart items. Let’s start by defining logic for a ADD_TO_CART action:
// src/index.js


const cartReducer = function(state=initialState, action) {
switch (action.type) {
case ADD_TO_CART: {
return {
cart: […state.cart, action.payload]

return state;

Take your time to analyze and understand the code. A reducer is expected to handle different action types, hence the need for a SWITCH statement. When an action of type ADD_TO_CART is dispatched anywhere in the application, the code defined here will handle it. As you can see, we’re using the information provided in action.payload to combine to an existing state in order to create a new state.
Next, we’ll define an action, which is needed as a parameter for store.dispatch(). Actions are simply JavaScript objects that must have type and an optional payload. Let’s go ahead and define one right after the cartReducer function:

function addToCart(product, quantity, unitCost) {
return {
type: ADD_TO_CART,
payload: { product, quantity, unitCost }

Here, we’ve defined a function that returns a plain JavaScript object. Nothing fancy. Before we dispatch, let’s add some code that will allow us to listen to store event changes. Place this code right after the console.log() statement:

let unsubscribe = store.subscribe(() =>


Next, let’s add several items to the cart by dispatching actions to the store. Place this code before unsubscribe():

store.dispatch(addToCart(‘Coffee 500gm’, 1, 250));
store.dispatch(addToCart(‘Flour 1kg’, 2, 110));
store.dispatch(addToCart(‘Juice 2L’, 1, 250));

For clarification purposes, I’ll illustrate below how the entire code should look after making all the above changes:
// src/index.js

import { createStore } from "redux";
import { combineReducers } from ‘redux’;

const productsReducer = function(state=[], action) {
return state;

const initialState = {
cart: [
product: ‘bread 700g’,
quantity: 2,
unitCost: 90
product: ‘milk 500ml’,
quantity: 1,
unitCost: 47


const cartReducer = function(state=initialState, action) {
switch (action.type) {
case ADD_TO_CART: {
return {
cart: […state.cart, action.payload]

return state;

function addToCart(product, quantity, unitCost) {
return {
type: ADD_TO_CART,
payload: {

const allReducers = {
products: productsReducer,
shoppingCart: cartReducer

const rootReducer = combineReducers(allReducers);

let store = createStore(rootReducer);

console.log("initial state: ", store.getState());

let unsubscribe = store.subscribe(() =>

store.dispatch(addToCart(‘Coffee 500gm’, 1, 250));
store.dispatch(addToCart(‘Flour 1kg’, 2, 110));
store.dispatch(addToCart(‘Juice 2L’, 1, 250));


After you’ve saved your code, Chrome should automatically refresh. Check the console tab to confirm that the new items have been added:

Figure 3: Redux Actions Dispatched

Continue reading %Getting Started with Redux%