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 README.md
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/ember.debug.map’
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/ember-testing.map’

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/ember.debug.map’
⠇ 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/ember-testing.map’
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%

Link: https://www.sitepoint.com/ember-js-perfect-framework-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%

Link: https://www.sitepoint.com/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%

Link: https://www.sitepoint.com/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%

Link: https://www.sitepoint.com/using-preact-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 wrapapi.com 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 (https://news.ycombinator.com/). 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 https://www.sitepoint.com/javascript/. 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%

Link: https://www.sitepoint.com/extracting-website-data-creating-apis-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. www.example.com/products.
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. example.com/products/shoes/101, 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
├── README.md
├── 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%

Link: https://www.sitepoint.com/react-router-v4-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%

Link: https://www.sitepoint.com/getting-started-redux/

Sharing React Components Easily with Bit

This is the age of components. Frameworks built for UI components, such as React, enable us to split our UI into individual, reusable pieces that can be worked with in isolation.
In many ways, React components are not that different from other encapsulated code functionalities. They can get defined inputs (usually “props” or ES6 classes) and return UI-oriented elements that will appear as part of your UI.
Individual components are often used across different parts of our UI. The problem is, organizing and sharing our components across teams and applications often presents a real challenge. Sharing components can give us fast and simple access to components written and used by our team, and help make sure our codebase is made of nothing but what we actually need.
Bit is an open-source project that enables us to instantly share components from our existing source code with our team, and use them across our different projects without changing our source code, file structure or the tools we work with. Let’s see how.

Sharing Components: It’s Not That Simple
Three major issues stand in the way of easily organizing and sharing source-code components: discoverability, maintainability, and the overhead of sharing.
Discoverability is a major issue. A developer working on my team on or a different team has no way of easily discovering and browsing the components available throughout our source code when choosing, upgrading or installing the ones they need with the tools of their choice.
Maintainability is another problem while sharing common components across different parts of our application. Maintainability problems range from simple duplications, to the complexity of maintaining multiple repos and packages and keeping control over the dependency chain. This can quickly get out of hand.
Up until now, sharing our components was a bit of a challenge. It forced us to either duplicate code or invest a lot of time and effort maintaining large packages — which also weigh down our build and install time.
When trying to find and use an individual React component (Slider, Spinner etc.) we usually ended up installing vast static libraries containing a whole bunch of stuff we didn’t need. It also made it next to impossible to discover or use individual components created by our team or the community.
In some ways, this is very much like using a CD-ROM just to listen to a single song. Using Bit, we can easily share any set of components, making them individually available to anyone on our team.
Sharing Components with Bit
If you haven’t heard of Bit’s latest release, it’s an open-source project that allows us to share components from our existing source code with our team and across projects.
By decoupling the representation of components from our actual file structure, Bit tracks the components within our source code and enables us to quickly turn any file or subset of files into a reusable component. Using simple glob patterns (see below), the components within an entire library or project can be instantly shared without changing our source code itself or our file structure.
Any component (installed with Bit, and very soon with NPM or Yarn) can be individually shared, discovered and used in any application or project. It can also be modified and updated from any project environment, choosing if and how to let our friends update our components from their own projects (and vice versa).

Components can be grouped together into “Scopes”, which are collections that can be thought of as “playlists” of individual components sharing common attributes. When using the free Bit community site, each component is presented along with its rendered visuals, test results, semi-automatically generated docs and more.
Regardless of the tools we use to install our components, we can gain full control over our dependency graph and get a clear picture of the components used across our projects. Sharing code can also help keep our UI aligned with our design principles, as we can avoid changes when implementing the same components again and again in different projects.
Let’s try an example.
Continue reading %Sharing React Components Easily with Bit%

Link: https://www.sitepoint.com/sharing-react-components-easily-bit/

Writing Server-rendered React Apps with Next.js

The dust has settled a bit as far as the JavaScript front-end ecosystem is considered. React has arguably the biggest mindshare at this point, but has a lot of bells and whistles you need to get comfortable with. Vue offers a considerably simpler alternative. And then there’s Angular/Ember which, while still popular, are not the first recommendations for starting a new project.
So, while React is the most popular option, it still requires lot of tooling to write production-ready apps. Create React App solves many of the pain points of starting, but the jury is still out on how long you can go without ejecting. And when you start looking into the current best practices around front-end, single-page applications (SPAs) — like server-side rendering, code splitting, and CSS-in-JS — it’s a lot to find your way through.
That’s where Next comes in.
Why Next?
Next provides a simple yet customizable solution to building production-ready SPAs. Remember how web apps were built in PHP (before “web apps” was even a term)? You create some files in a directory, write your script and you’re good to deploy. That’s the kind of simplicity Next aims at, for the JavaScript ecosystem.
Next is not a brand new framework per se. It fully embraces React, but provides a framework on top of that for building SPAs while following best practices. You still write React components. Anything you can do with Next, you can do with a combination of React, Webpack, Babel, one of 17 CSS-in-JS alternatives, lazy imports and what not. But while building with Next, you aren’t thinking about which CSS-in-JS alternative to use, or how to set up Hot Module Replacement (HMR), or which of many routing options to choose. You’re just using Next — and it just works.

I’d like to think I know a thing or two about JavaScript, but Next.JS saves me an ENORMOUS amount of time. — Eric Elliott

Getting Started
Next requires minimal setup. This gets you all the dependencies you need for starting:
$ npm install next react react-dom –save

Create a directory for your app, and inside that create a directory called pages. The file system is the API. Every .js file becomes a route that gets automatically processed and rendered.
Create a file ./pages/index.js inside your project with these contents:
export default () => (

Hello, Next!</div>

Populate package.json inside your project with this:
“scripts": {
"dev": "next",
"build": "next build",
"start": "next start"

Then just run npm run dev in the root directory of your project. Go to http://localhost:3000 and you should be able to see your app, running in all its glory!
Just with this much you get:

automatic transpilation and bundling (with Webpack and Babel)
Hot Module Replacement
server-side rendering of ./pages
static file serving: ./static/ is mapped to /static/.

Good luck doing that with Vanilla React with this much setup!
Continue reading %Writing Server-rendered React Apps with Next.js%

Link: https://www.sitepoint.com/writing-server-rendered-react-apps-next-js/