Using Preact as a React Alternative

SitePoint - Fri, 09/29/2017 - 13:00

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

SitePoint - Fri, 09/29/2017 - 11:00

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.

Tips:

  • 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

SitePoint - Thu, 09/28/2017 - 11:00

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:

<div id="myApp"> <nav aria-label="Page navigation example"> <ul class="pagination"> <li class="page-item"><a class="page-link" href="#">1</a></li> <li class="page-item"><a class="page-link" href="#">2</a></li> <li class="page-item active"><a class="page-link" href="#">3</a></li> <li class="page-item"><a class="page-link" href="#">4</a></li> <li class="page-item"><a class="page-link" href="#">5</a></li> </ul> </nav> </div>

Notice that each page in this code snippet has a list item element (<li …). That element references the page-item CSS class. In the code for this article, this class is defined in the Bootstrap CSS framework. However, if it weren't defined there, it would be your responsibility to ensure that it was defined somewhere. The second CSS class is the one that's most relevant to this article, though.

The active CSS class is used to identify the currently selected page. For this article, this CSS class is also defined in the Bootstrap CSS. As shown in the snippet above, the active class is only used in the third list item element. As you can probably guess, this is the CSS class that you want to apply conditionally. To do that, you need to add a JavaScript object.

Continue reading %Conditionally Applying a CSS Class in Vue.js%

120+ Places To Find Creative Commons Media

SitePoint - Thu, 09/28/2017 - 10:00

The number of images, audio files, movies and other files available under a Creative Commons license is enormous, as Sean demonstrates in this post. Check out his list of over 30 useful sites for sourcing Creative Commons media.

Continue reading %120+ Places To Find Creative Commons Media%

How to Design Highly Memorable Experiences, and Why

SitePoint - Wed, 09/27/2017 - 11:00

According to Gartner, by 2017, 89% of marketers expect customer experience to be their primary differentiator. In order to create terrific customer experiences that set our apps and websites apart, we need to learn a bit more about how our brains work, and how we can create experiences that are memorable.

Fact: human brains are lazy. We love a shortcut.

Let's take a look at how that impacts on the way we design user experiences, and how we can design for lazy brains.

The Peak—end Rule

Nobel Prize winner Daniel Kahneman suggested that modern-day humans employ a a psychological heuristic (basically, a mental shortcut) called the peak—end rule, which states:

People judge an experience largely based on how they felt at its peak (i.e., its most intense point) and at its end, rather than based on the total sum or average of every moment of the experience. The effect occurs regardless of whether the experience is pleasant or unpleasant.

Let's think about that for a second. It's a big deal.

When we remember experiences, we tend to recall only snapshots of the key events that happened. This means that we might easily recall a singular negative event (like a rude customer service representative) and forget the better but smaller aspects of the experience (like a well-designed website). Or, vice versa, we might dislike an experience overall (bad website UX), but what we'll remember later is the terrific customer service received.

The Peak–end Rule: an Everyday Example

An everyday example of this is movies. Have you ever watched a brilliant movie, only for it to be spoiled by a disappointing ending? Two hours of spellbinding suspense can be rendered useless with a bad ending, much like an exciting online shopping experience can be ruined by a confusing/frustrating checkout.

Even if the middle of the experience was faultless, that's not the aspect of the experience that users will remember.

Boost Peak Moments with Friction

So we know that our brains like shortcuts. We know they remember the end and the most intense moments of an experience more than any other moment. In addition to that, we should also remember that our memories are faulty; they aren't always correct. People won't always remember what you said to them, but they'll remember how you made them feel.

So, with that in mind, we can then make changes to the experience to ensure that users forget negative moments, and remember positive ones. Some menial tasks, such as filling out a form, users won't want to remember. By simplifying the experience and removing friction, users can breeze through this step. We don't want the peak moment to be a horrendous one.

Airbnb Example

The same applies to positive experiences. Let's say you've booked an apartment on Airbnb. That's pretty exciting, right? Of course it is: you're going on holiday! To ensure the possibly frustrating search experience doesn't overshadow the excitement of your booking, Airbnb adds friction to keep you excited for a little longer. Here's what Airbnb does:

  • shows you things to do in the area
  • lets you read the house manual
  • lets you send the itinerary to your travel buddies
  • helps you find directions to the address
  • sends you an exciting "You're going away!" message

Not only does this often overshadow the somewhat long/boring search for an Airbnb, but it improves the user experience towards the end as well. Now, when the user remembers Airbnb, they'll remember how exciting it all was. Even though Airbnb bothers us with sending itineraries and recommendations, this is the sort of friction we're happy to engage in.

In short: stretch out positive moments, and relieve the user of negative pain points quickly by removing friction.

Uber Example

Remember taxis? Remember arriving at your destination and then fiddling around for cash? Yeah, this can be awkward. You realize you don't have the right change, so you pay with credit card; the card machine isn't working, so you have to drive to the ATM.

It's a rather awful, frustrating, embarrassing experience.

Your Uber account is linked to your bank card. Once you've arrived at your destination, you hop out of the car and you're done. Fiddling around for cash is not necessary; that pain point has been removed, and so the user walks away with their final experience with Uber being one of delight.

Embrace "Flat" Moments

Flat moments are moments that are neither fun nor boring.

An excellent example of a "flat moment turned memorable" might be from way back in the early 2000s, from an e-commerce website called CD Baby. Typically, when you make a purchase online, you receive an email confirmation to notify you that your purchase went through smoothly. This is fairly standard, and important.

Derek Sivers at CD Baby knew how flat this experience would be, and didn't want to end it with something that wasn't memorable, so he thought he'd have some fun. He put on his best copywriting mitts and came up with the following confirmation email:

People loved it. It went viral. Derek had turned a boring aspect of the experience into an unexpected delight. People were suddenly purchasing from CD Baby just to see the email (remember, this was the early 2000s!). If we map out the customer journey, we'll find that the email had become a peak moment, and a surefire way to create a memorable experience as the user --- hopefully temporarily --- departs from CD Baby.

Continue reading %How to Design Highly Memorable Experiences, and Why%

React Router v4: The Complete Guide

SitePoint - Tue, 09/26/2017 - 13:00

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.

Introduction

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":

<Route path="/about" component={About}/>

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.

Overview

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:

  1. basic navigational routing
  2. nested routing
  3. nested routing with path parameters
  4. 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:

react-routing-demo-v4 ├── .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:

<Router> <Route exact path="/" component={Home}/> <Route path="/category" component={Category}/> <Route path="/login" component={Login}/> <Route path="/products" component={Products}/> </Router> Router

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:

  1. <BrowserRouter>
  2. <HashRouter>

The primary difference between them is evident in the URLs that they create:

// <BrowserRouter> http://example.com/about // <HashRouter> http://example.com/#/about

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.

index.js /* 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'; ReactDOM.render( <BrowserRouter> <App /> </BrowserRouter> , 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

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 src/App.js /* Import statements */ import React, { Component } from 'react'; import { Link, Route, Switch } from 'react-router-dom'; /* Home component */ const Home = () => ( <div> <h2>Home</h2> </div> ) /* Category component */ const Category = () => ( <div> <h2>Category</h2> </div> ) /* Products component */ const Products = () => ( <div> <h2>Products</h2> </div> ) /* App component */ class App extends React.Component { render() { return ( <div> <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> </ul> </nav> /* 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}/> </div> ) } }

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

SitePoint - Tue, 09/26/2017 - 12:00

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.

Prerequisites

Before we get started, make sure you're familiar with the following topics:

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

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:

node

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:

  1. using immutable data structures created by Immutable.js
  2. using JavaScript libraries such as Underscore and Lodash to execute immutable operations
  3. 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:

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 ADD_TO_CART = 'ADD_TO_CART'; const cartReducer = function(state=initialState, action) { switch (action.type) { case ADD_TO_CART: { return { ...state, cart: [...state.cart, action.payload] } } default: 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(() => console.log(store.getState()) ); unsubscribe();

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 ADD_TO_CART = 'ADD_TO_CART'; const cartReducer = function(state=initialState, action) { switch (action.type) { case ADD_TO_CART: { return { ...state, cart: [...state.cart, action.payload] } } default: return state; } } function addToCart(product, quantity, unitCost) { return { type: ADD_TO_CART, payload: { product, quantity, unitCost } } } const allReducers = { products: productsReducer, shoppingCart: cartReducer } const rootReducer = combineReducers(allReducers); let store = createStore(rootReducer); console.log("initial state: ", store.getState()); let unsubscribe = store.subscribe(() => console.log(store.getState()) ); store.dispatch(addToCart('Coffee 500gm', 1, 250)); store.dispatch(addToCart('Flour 1kg', 2, 110)); store.dispatch(addToCart('Juice 2L', 1, 250)); unsubscribe();

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%

15 Top Prototyping Tools Go Head-to-Head

SitePoint - Tue, 09/26/2017 - 11:00

As the number and variety of prototyping tools continues to grow, it’s becoming harder and harder to figure out which tools meet what needs, and who they’re suitable for. Since we first wrote this article back in 2015, countless design apps have dominated (and changed) the prototyping space.

Stakeholder feedback and user testing is now taking a far greater role in UI design and this new generation of tools aims to connect these two previously separate stages of the design process. Clients want to be involved, and email isn’t cutting it anymore. Some apps like UXPin are also taking care of the wireframing stages, whereas others like InVision App are bridging the gap between designer and developer by offering design handoff tools.

Plus, there’s now a clear divide between desktop tools with cloud sharing (Adobe XD, Axure, Balsamiq, Sketch+InVision) and collaborative online tools (Figma, UXPin, Fluid UI, Proto.io).

Many of these tools appear to be converging on a feature set that defines the role of the modern user experience designer. TL;DR—here’s a swift comparison of prototyping tools.

Adobe XD

Adobe may have been caught napping during the rise of Sketch, but they’re rapidly making up for it with Adobe XD. Launched in March 2016, and still in beta as of July 2017, it’s the latest addition to Adobe’s Creative Cloud Suite. While you can prototype interactions in Sketch with the help of the Craft Plugin, Adobe XD impressively offers these tools right out of the box, so designers are already comparing Adobe XD to Sketch like longtime rivals.

It’s definitely worth a look if you’re interested in a tool that covers all your bases (low-fidelity prototyping, high-fidelity prototyping, user flows, sharing and feedback) in a single app.

Strengths

  • Available for macOS and Windows
  • Everything you need in a single app

Weaknesses

  • Still in beta (although pleasantly mature as a design app)
  • Plugin workflow non-existent, you’re locked into the Adobe ecosystem
InVision App (with Sketch and Craft)

InVision App is the largest and most successful design collaboration tool currently on the market, the primary go-to tool for serious designers and enterprise teams alike. With tools like whiteboard collaboration, dynamic prototyping, comments, device preview, video calling, user testing, version control and design handoff, InVision is already a colossal force in the prototyping space, but when you factor in its Sketch and Photoshop integrations, it becomes an all-in-one design suite, especially when you throw in Craft, the Sketch/Photoshop Plugin that brings a lot of that functionality directly into your design app of choice.

Strengths

  • Powerful, mature platform
  • Fully-integrated with Sketch for high-fidelity design
  • Constantly being updated with new features

Weaknesses

  • Feature-set can be a little overwhelming at first
  • Sketch is only available for macOS users only (but you can pair InVision with Photoshop on Windows, although Photoshop isn’t strictly a UI design tool)
Marvel App

A very strong favourite for those looking for simpler, friendlier alternatives to InVision App. Marvel App has excelled at creating a prototyping tool that works for both advanced UX designers and those simply looking to communicate high and low fidelity concepts. Plus, while they champion working with Sketch, they also offer component libraries to allow for a complete online workflow in Marvel. Marvel App also recently integrated fan-favourite POP, which allows designers to transform their pen/paper ideas into iPhone and Android apps.

Strengths

  • Great support for transitions for additional realism
  • Friendlier for non-designers, especially when giving feedback

Weaknesses

  • Web based only
  • No offline designing
UXPin

UXPin is the most complete online solution for UX designers in terms of their offering. While you can import from Sketch and Photoshop, you can also design complex and responsive interfaces with UXPin’s built-in libraries, making UXPin something of a wireframing tool as well. With their design systems features, UXPin becomes one of the most complex tools in terms of automated documentation, designer/developer handoffs and collaborative features.

Strengths

  • Responsive design with breakpoints
  • Powerful animations (not just linking screens)
  • Complete design collaboration and handoff solution

Weaknesses

  • A little pricey versus the competition at $49/user/month
  • Additional features increase the complexity of use
Webflow

Webflow is a visual tool for designing responsive websites that also exports clean code—it removes the headache of going from design to published on the web. Competing as much with WordPress as it does with Sketch App, Webflow lets you design fully functional responsive websites incorporating back-end (API) data and can automatically deploy to fully scalable, worry-free hosting with a single click of a button. It’s basically Adobe Dreamweaver for the modern-day designer who cares about clean code and mobile-friendly web design.

Strengths

  • Real data can be included (from APIs/JSON/etc)
  • Creates high-quality, reusable code
  • Responsive websites can be designed and deployed with ease

Weaknesses

  • Not useful for designing native mobile apps
  • Requires some knowledge of HTML/CSS to be at its most effective
Figma

A somewhat recent addition to the prototyping space, Figma boasts the most mesmerising real-time design collaboration features of any prototyping tool while modelling its feature-set on many of the intuitive design tools of Sketch and Adobe XD (such as symbols and device preview), along with a bunch of tools usually reserved for the online crowd (such as versioning and design handoff). Version 2.0, launched in July 2017, includes a prototyping mode with hotspots and developer handoffs to further streamline the design workflow. It works in the browser, on macOS, and on WIndows, although it sometimes can be slow.

Strengths

  • Real-time collaborative design features are second-to-none
  • Fully-featured, ideal for designers from start to finish

Weaknesses

  • Figma can can be laggy at time, especially with real-time collaboration
9 More Prototyping Tools Worth Considering Fluid UI

With a strong focus on simplicity and communication, Fluid UI includes built-in high and low fidelity component libraries, live team collaboration, device previews and video presentations making it a top-notch solution for designers, product managers and founders alike.

Proto.io

Mature and feature-rich, Proto.io is best used by designers looking to create high-fidelity and highly-animated prototypes in the browser.

Axure RP 8

Established way back in 2003, Axure is an excellent choice for UX designers who need to create specifications for designs and animations in supreme detail. Axure’s includes support for conditional flow interactions, dynamic content and adaptive/responsive design, as well as high and low-fidelity prototyping. Axure is a serious tool for serious designers.

Continue reading %15 Top Prototyping Tools Go Head-to-Head%

CSS font-display: The Future of Font Rendering on the Web

SitePoint - Tue, 09/26/2017 - 09:00

One of the downsides of using web fonts is that if a font is not available on a user’s device, it must be downloaded. This means that before the font becomes available the browser has to decide how to handle the display of any block of text that uses that font. And it needs to do so in a way that doesn’t significantly impact the user experience and perceived performance.

In the course of time, browsers have adopted several strategies to mitigate this problem. But they do this in different ways and out of the control of developers, who have had to devise several techniques and workarounds to overcome these issues.

Enter the font-display descriptor for the @font-face at-rule. This CSS feature introduces a way to standardize these behaviors and provide more control to developers.

Using font-display

Before looking in detail at the various features offered by font-display, let’s briefly consider how you might use the feature in your CSS.

First of all, font-display is not a CSS property but, as mentioned in the intro, it is a descriptor for the @font-face at-rule. This means that it must be used inside a @font-face rule, as showed in the following code:

[code language="css"]
@font-face {
font-family: 'Saira Condensed';
src: url(fonts/sairacondensed.woff2) format('woff2');
font-display: swap;
}
[/code]

In this snippet I’m defining a swap value for the font Saira Condensed.

The keywords for all the available values are:

  • auto
  • block
  • swap
  • fallback
  • optional

The initial value for font-display is auto.

In later sections I’ll go over each of these values in detail. But first, let’s look at the time period that the browser uses to determine the font to be rendered. When discussing each of the values, I’ll explain the different aspects of the timeline and how these behave for each value.

The font-display Timeline

At the core of this feature is the concept of the font-display timeline. The font loading time, starting from its request and ending with its successful loading or failure, can be divided into three consecutive periods that dictate how a browser should render the text. These three periods are as follows:

  • The block period. During this period, the browser renders the text with an invisible fallback font. If the requested font successfully loads, the text is re-rendered with that requested font. The invisible fallback font acts as a blank placeholder for the text. This reduces layout shifting when the re-rendering is performed.
  • The swap period. If the desired font is not yet available, the fallback font is used, but this time the text is visible. Again, if the loading font comes in, it is used.
  • The failure period. If the font does not become available, the browser doesn’t wait for it, and the text will be displayed with the fallback font on the duration of the current page visit. Note that this doesn’t necessarily mean that the font loading is aborted; instead, the browser can decide to continue it, so that the font will be ready for use on successive page visits by the same user.

Continue reading %CSS font-display: The Future of Font Rendering on the Web%

Sharing React Components Easily with Bit

SitePoint - Mon, 09/25/2017 - 13:00

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%

Getting React Projects Ready Fast with Pre-configured Builds

SitePoint - Wed, 09/06/2017 - 12:00

Starting a new React project now days is not as simple as we'd like it to be. Instead of instantly diving into the code and bringing your application to life, you have to spend time configuring the right build tools to set up a local development environment, unit testing, and a production build. But there are projects where all you need is a simple set up to get things running quickly and with minimal efforts.

Create-react-app provides just that. It's a CLI tool from Facebook which allows you to generate a new React project and use a pre-configured Webpack build for development. Using it, you will never have to look at the Webpack config again.

How does create-react-app work?

Create-react-app is a standalone tool which should be installed globally via npm, and called each time you need to create a new project.

npm install -g create-react-app

To create a new project, run:

create-react-app react-app

Create-react-app will set up the following project structure:

. ├── .gitignore ├── README.md ├── package.json ├── node_modules ├── public │ ├── favicon.ico │ └── index.html └── src ├── App.css ├── App.js ├── App.test.js ├── index.css ├── index.js └── logo.svg

It will also add a react-scripts package to your project which will contain all of the configuration and build scripts. In other words, your project depends react-scripts, not on create-react-app itself. Once the installation is complete, you can start working on your project.

Starting a Local Development Server

The first thing you'll need is a local development environment. Running npm start will fire up a Webpack development server with a watcher which will automatically reload the application once you change something. Hot reloading, however, is only supported for styles.

The application will be generated with a number of features built-in.

ES6 and ES7

The application comes with its own Babel preset, babel-preset-react-app, to support a set of ES6 and ES7 features. It even supports some of the newer features like async/await, and import/export statements. However, certain features, like decorators, have been intentionally left out.

Continue reading %Getting React Projects Ready Fast with Pre-configured Builds%

10 Unexpected Sources of Design Inspiration

SitePoint - Tue, 09/05/2017 - 13:00

There's a source of inspiration for every type of design you can think of. Struggling to create the perfect font pairing? Head to Typewolf. Searching for ideas for your website redesign, or a specific webpage? Browse Crayon. Looking for all-around epic sources of design inspiration? Check out the latest crop of Webby Award winners.

But as awesome as these collections are, it's dangerous to rely on them exclusively. If all designers are referencing the same ideas, concepts and templates from the same websites for design inspiration, every design then sort-of becomes a variation of an existing one. It's almost impossible to create something novel or unique, when all designers are basing their ideas on the same inspiration sources.

Luckily, there's a solution for that...

Throw some new sources of design inspiration into the mix, alongside your regular sources! These 10 websites will keep you inspired in unexpected ways.

1. 99% Invisible

99% Invisible is a blog and radio show hosted by Roman Mars. It delves into the unnoticed yet beautiful, intriguing and significant forces that shape our world.

In other words…the 99%.

Each episode is approximately 15-25 minutes long and covers a single topic related to architecture, objects, visuals, history, technology, society, cities, sounds and infrastructure. Not only will it help you look at your surroundings with fresh eyes, but it'll help you hone your attention to detail. It's the "little things" that often make or break a design, so an enhanced focus on little details is definitely a skill worth mastering.

2. The Dieline

My grocery trips have been taking twice as long since I discovered The Dieline. This epic website features at least one innovative packaging design per day, but often shares two or three. You'll be both surprised and delighted to see how the most mundane items (like pencils) can be elevated by logo design and clever packaging.

The fundamentals of design apply to packaging like any other aspect of design. For example, if there's not enough white space in the design on a bag of coffee, it'll look crowded and strain the consumer's eyes when they're trying to read it in the supermarket, resulting in a loss of sale. Because these design concepts carry over in many ways, scrolling through The Dieline will reinforce your existing design knowledge regardless of whether you're you're a logo, web or user interface designer.

3. The Great Discontent (TGD)

The Great Discontent is a print and digital magazine showcasing all types of creatives from photographers and graphic designers to illustrators and filmmakers. Unlike many other design inspiration sources, TGD features the astonishing designers behind the work, not the only works themselves.

Sometimes it can be even more inspiring to read about an artist's beginnings, their current projects, and the biggest challenges they've faced, than to see the work itself.

After all, creative work can be emotionally draining, since you're not using up both your physical and mental strength equally, but rather 100% (and sometimes more!) of your mental strength. Knowing that others can relate often rejuvenates you and inspires you to carry on. You'll also learn how other creatives generate their amazing ideas.

4. Design Milk

Design Milk never lets me down when I need straight-up visual eye-candy. This online magazine curates the best art, interior design, furniture, fashion, technology and architecture from around the world. The photographs are stunning, the cultures and aesthetics are stylistically varied but universally interesting, and the writing is solid. If you need bursts of inspiration from a variety of different art concepts, Design Milk is definitely for you.

And, if you're only interested in a specific vertical—say, architecture—it's easy to filter out other content and narrow down your search.

5. Style Guides by Brad Frost

Nothing fuses the creative and the orderly together like a style guide. Brad Frost, well-known front-end designer and author of Atomic Design, created Style Guides to house an ever-growing collection of resources on the topic. The Talks and Tools sections are certainly worth scrolling through, although my favorite is Examples. You'll find some of the most well-crafted style guides in existence, from the biggest brands today.

Better yet, you can sort through them by their content.

6. Card Nerd

Counterintuitively, rules and restrictions often inspire some of the most inventive designs. After all, they force you to find unexpected solutions and workarounds, where a "no-limits" approach has the tendency to make designers feel lazy.

This explains why business cards are a reliable source of inspiration. A business card designer has a tiny medium for a big task: communicating someone's professional identity. Whenever you're struggling to pare down your copy to the essentials, or make a design feel less busy, use Card Nerd. This gallery is updated several times a day with new business cards, ranging from minimalist to bold and colorful.

Continue reading %10 Unexpected Sources of Design Inspiration%

React vs Angular: An In-depth Comparison

SitePoint - Tue, 09/05/2017 - 12:00

Should I choose Angular, or React? Today's bipolar landscape of JavaScript frameworks has left many of developers struggling to pick a side in this debate. Whether you're a newcomer trying to figure out where to start, a freelancer picking a framework for your next project or an enterprise-grade architect planning a strategic vision for your company, you're likely to benefit from having an educated view on this topic.

To save you some time, let me tell you something up front: this article won't give a clear answer on which framework is better. But neither will hundreds of other articles with similar titles. I can't tell you that because the answer depends on a wide range of factors which make a particular technology more or less suitable for your environment and use case.

Since we can't answer the question directly, we'll attempt something else. We'll compare Angular (2+, not the old AngularJS) and React to demonstrate how you can approach the problem of comparing any two frameworks in a structured manner on your own and tailor it to your environment. You know, the old "teach a man to fish" approach. That way, when both are replaced by a BetterFramework.js in a year's time, you will be able to re-create the same train of thought once more.

Where to Start?

Before you pick any tool you need to answer two simple questions: "Is this a good tool per se?" and "Will it work well for my use case?" None of them mean anything on their own, so you always need to keep both of them in mind. All right, the questions might not be that simple, so we'll try to break them down into smaller ones.

Questions on the tool itself:

  • How mature is it and who's behind it?
  • What kind of features does it have?
  • What architecture, development paradigms, and patterns does it employ?
  • What is the ecosystem around it?

Questions for self-reflection:

  • Will I and my colleagues be able to learn this tool with ease?
  • Does is fit well with my project?
  • What is the developer experience like?

Using this set of questions you can start your assessment of any tool and we'll base our comparison of React and Angular on them as well.

There's another thing we need to take into account. Strictly speaking, it's not exactly fair to compare Angular to React, since Angular is a full-blown feature-rich framework, and React just a UI component library. To even the odds, we'll talk about React in conjunction with some of the libraries often used with it.

Maturity

An important part of being a skilled developer is being able to keep the balance between established, time-proven approaches and evaluating new bleeding-edge tech. As a general rule, you should be careful when adopting tools which have not yet matured due to certain risks:

  • The tool might be buggy and unstable.
  • It might be unexpectedly abandoned by the vendor.
  • There might not be a large knowledge base or community available in case you need help.

Both React and Angular come from good families, so it seems that we can be confident in this regard.

React

React is developed and maintained by Facebook and used in their own products, including Instagram and WhatsApp. It has been around for roughly three and a half years now, so it's not exactly new. It's also one of the most popular projects on GitHub with about 60,000 stars at the time of writing. Sounds good to me.

Angular

Angular (version 2 and above) has been around less then React, but if you count in the history of its predecessor, AngularJS, the picture evens out. It's maintained by Google and used in AdWords and Google Fiber. Since AdWords is one of the key projects in Google, it is clear they have made a big bet on it and is unlikely to disappear anytime soon.

Features

Like I mentioned earlier, Angular has more features out of the box than React. This can be both a good and a bad thing, depending on how you look at it.

Both frameworks share some key features in common: components, data binding, and platform-agnostic rendering.

Angular

Angular provides a lot of the features required for a modern web application out of the box. Some of the standard features are:

  • Dependency injection;
  • Templates, based on an extended version of HTML;
  • Routing, provided by @angular/router;
  • Ajax requests by @angular/http;
  • @angular/forms for building forms;
  • Component CSS encapsulation;
  • XSS protection;
  • Utilities for unit-testing components.

Having all of these features available out of the box is highly convenient when you don't want to spend time picking the libraries yourself. However, it also means that you're stuck with some of them, even if you don't need them. And replacing them will usually require additional effort. For instance, we believe that for small projects having a DI system creates more overhead than benefit, considering it can be effectively replaced by imports.

React

With React, you're starting off with a more minimalistic approach. If we're looking at just React, here's what we have:

  • No dependency injection;
  • Instead of classic templates it has JSX, an XML-like language built on top of JavaScript;
  • XSS protection;
  • Utilities for unit-testing components.

Not much. And this can be a good thing. It means that you have the freedom to choose whatever additional libraries to add based on your needs. The bad thing is that you actually have to make those choices yourself. Some of the popular libraries that are often used together with React are:

We've found the freedom of choosing your own libraries liberating. This gives us the ability to tailor our stack to particular requirements of each project and we didn't find the cost of learning new libraries that high.

Languages, Paradigms, and Patterns

Taking a step back from the features of each framework, let's see what kind higher-level concepts are popular with both frameworks.

React

There are several important things that come to mind when thinking about React: JSX, Flow, and Redux.

JSX

JSX is a controversial topic for many developers: some enjoy it, and others think that it's a huge step back. Instead of following a classical approach of separating markup and logic, React decided to combine them within components using an XML-like language that allows you to write markup directly in your JavaScript code.

While the topic of mixing markup with JavaScript might be debatable, it has an indisputable benefit: static analysis. If you make an error in your JSX markup, the compiler will emit an error instead of continuing in silence. This helps by instantly catching typos and other silly errors. This is something we really miss in Angular.

Flow

Continue reading %React vs Angular: An In-depth Comparison%

A Guide to Setting Up Let’s Encrypt SSL on Shared Hosting

SitePoint - Tue, 09/05/2017 - 11:00

In recent years, there's been a strong push by Google and others to make the web more secure by encouraging the use of TLS/SSL (transport layer security/secure sockets layer) on every website.

Google has added extra encouragement for using HTTPS by giving a ranking boost to sites, and, like other browser makers, is gradually turning up the heat in Chrome by introducing increasingly alarming alerts on sites without encryption.

Until recently, SSL certificates were quite costly. Let's Encrypt changed that by offering free certificates.

There are lots of online tutorials showing how to install Let's Encrypt certificates, but they tend to require quite a bit of technical expertise (knowledge of how to operate a Linux web server and manage root access) and rarely guide you on how to install it through a common shared hosting control panel. If your cPanel or other control panel instance doesn't provide a feature like One Click Install for Let's Encrypt SSL (and many don't), then you may feel there's no option but to fork out money for a certificate through your web hosting provider.

However, in this article I'll show you how to install a Let's Encrypt SSL certificate on your shared web hosting server using the services from SSL For Free. SSL For Free allows you to install a Let's Encrypt SSL certificate without having to have root access and a VPS, but just a regular shared web hosting server.

Installing Let's Encrypt SSL Using SSL For Free

Step 1: Head over to the SSL For Free website.

Step 2: In the enter your website to secure input box, type your website domain address (for example: yourdomain.com).

Step 3: SSL For Free will provide SSL certificates for yourdomain.com and www.yourdomain.com automatically.

Step 4: If you want to add another subdomain (for example: sub.yourdomain.com), click the Add / Edit Domains link, and you'll be returned to the domain address input page.

Step 5: Add the subdomain you desire in the input box.

Verify your domain and/or subdomain by SSL For Free

There are three ways to verify your domain by SSL For Free (you can choose any one of them).

  1. The first is via Automatic FTP Verification. Here, you'll be asked for data about your web hosting FTP account.
  2. The second is through Manual Verification. You'll be prompted to download two files from SSL For Free, which you'll later upload to your web hosting server.
  3. The third is through Manual Verification (DNS). This way, you'll be prompted to create a new TXT record through your web hosting control panel.

Let's take a look at each of the verification steps.

Method 1. Automatic FTP Verification

Step 1: Click the Automatic FTP Verification button.

Step 2: Below this, you'll be prompted to input data from your web hosting FTP account. Input the data completely:

If you feel uncomfortable with this way (giving your FTP account access data), then you can choose the second way (which I highly recommend) below.

Method 2. Manual Verification

Step 1: You'll be prompted to download two files generated by SSL For Free, which you'll then upload to your web hosting server. Click Manual Verification. (Note: don't close this tab/page!)

Step 2: Below, you'll be prompted to download two files generated by SSL For Free. Download both files, saving them on your local computer.

Step 3: In accordance with the instructions of this SSL For Free page, create a new folder/directory called .well-known. (If you're in a Windows environment, name it .well-known. --- that is, with an extra dot at the end.) Inside that directory, create a new directory called acme-challenge. Copy-paste the two downloaded files into the acme-challenge directory.

Step 4: Now upload both files to your web hosting server using your preferred FTP application (such as FileZilla).

Step 5: Upload the .well-known directory from your local computer to the root directory of your web hosting server (its directory, not the contents in it).

Step 6: Now open a new tab/page in your browser and enter your domain URL, along with the location of the two files. Make sure you see the random numbers and letters:

Step 7: Go back to the SSL For Free tab/page (page at Step 1) and click Download SSL Certificate. Make sure you don’t get a reply like this:

Step 8: If you get an error reply, please repeat Step 1 above, until SSL For Free loads the Loading SSL Certificate Account page. It will then proceed to the Generating SSL Certificate Securely page:

Method 3. Manual Verification (DNS)

In this last verification method option, you'll be prompted to create a new TXT record in your web hosting control panel.

Here's what the steps look like in cPanel:

Step 1: Click the Manual Verification (DNS) button on the SSL For Free site.

Step 2: You'll then be prompted to create a new TXT record according to the data on that page:

Step 3: Open a new tab/page in your browser and log in to CPanel on your server. Go to Zone Editor, and add a record with the following data:

  • Type: TXT
  • Name: _acme-challenge.yourdomain.com.
  • TTL: 14400
  • TXT Data: [corresponding to the first TXT Record data in Step 2]

Click Add Record:

Step 4: Then add the second new TXT record with the following data:

  • Type: TXT
  • Name: _acme-challenge.www.yourdomain.com.
  • TTL: 14400
  • TXT Data: [corresponding to the second TXT Record data in Step 2]

Once again, click Add Record.

Step 5: The final result will look something like this:

Step 6: Go back to the SSL For Free tab/page (page at Step 1) and click the Download SSL Certificate. If you've set up the TXT records correctly, you should get a couple of results like this:

Step 7: You'll be taken to the Loading SSL Certificate Account page, and then to the Generating SSL Certificate Securely page:

Continue reading %A Guide to Setting Up Let’s Encrypt SSL on Shared Hosting%

Building a Trello Layout with CSS Grid and Flexbox

SitePoint - Tue, 09/05/2017 - 09:00

In this tutorial, I’ll walk you through an implementation of the basic layout of a Trello board screen (see example here). This is a responsive, CSS-only solution, and only the structural features of the layout will be developed.

For a preview, here is a CodePen demo of the final result.

Besides Grid Layout and Flexbox, the solution employs calc and viewport units. To make the code more readable and efficient, I’ll also take advantage of Sass variables.

No fallbacks are provided, so make sure to run the code in a supporting browser. Without further ado, let’s dive in, developing the screen components one by one.

The Screen Layout

The screen of a Trello board consists of an app bar, a board bar, and a section containing the card lists. I’ll build this structure with the following markup skeleton:

[code language="html"]
<div class="ui">
<nav class="navbar app">...</nav>
<nav class="navbar board">...</nav>
<div class="lists">
<div class="list">
<header>...</header>
<ul>
<li>...</li>
...
<li>...</li>
</ul>
<footer>...</footer>
</div>
</div>
</div>
[/code]

This layout will be achieved with a CSS Grid. Specifically, a 3x1 grid (that is, one column and three rows). The first row will be for the app bar, the second for the board bar, and the third for the .lists element.

The first two rows each have a fixed height, while the third row will span the rest of the available viewport height:

[code language="sass"]
.ui {
height: 100vh;
display: grid;
grid-template-rows: $appbar-height $navbar-height 1fr;
}
[/code]

Viewport units ensure that the .ui container will always be as tall as the browser’s viewport.

A grid formatting context is assigned to the container, and the grid rows and columns specified above are defined. To be more precise, only the rows are defined because there is no need to declare the unique column. The sizing of the rows is done with a couple of Sass variables for the height of the bars and the fr unit to make the height of the .lists element span the rest of the available viewport height.

The Card Lists Section

As mentioned, the third row of the screen grid hosts the container for the card lists. Here’s the outline of its markup:

[code language="html"]
<div class="lists">
<div class="list">
...
</div>
...
<div class="list">
...
</div>
</div>
[/code]

I’m using a full viewport-width Flexbox single-line row container to format the lists:

[code language="sass"]
.lists {
display: flex;
overflow-x: auto;
> * {
flex: 0 0 auto; // 'rigid' lists
margin-left: $gap;
}
&::after {
content: '';
flex: 0 0 $gap;
}
}
[/code]

Assigning the auto value to the overflow-x property tells the browser to display a horizontal scrollbar at the bottom of the screen when the lists don’t fit in the width provided by the viewport.

Continue reading %Building a Trello Layout with CSS Grid and Flexbox%

How to Tell if React is the Best Fit for Your Next Project

SitePoint - Mon, 09/04/2017 - 13:00

Nowadays, users expect sleek, performant web applications that behave more and more like native apps. Techniques have been devised to decrease the waiting time for a website to load on a user's first visit. However, in web applications that expose a lot of interactivity, the time elapsing between a user action taking place and the app's response is also important. Native apps feel snappy, and web apps are expected to behave the same, even on less than ideal internet connections.

A number of modern JavaScript frameworks have sprung up that can be very effective at tackling this problem. React can be safely considered among the most popular and robust JavaScript libraries you can use to create fast, interactive user interfaces for web apps.

In this article, I'm going to talk about what React is good at and what makes it work, which should provide you with some context to help you decide if this library could be a good fit for your next project.

What Is React?

React is a Facebook creation which simply labels itself as being a JavaScript library for building user interfaces.

It's an open-source project which, to date, has raked in over 74,000 stars on GitHub.

React is:

  • Declarative: you only need to design simple views for each state in your application, and React will efficiently update and render just the right components when your data changes.
  • Component-based: you create your React-powered apps by assembling a number of encapsulated components, each managing its own state.
  • Learn Once, Write Anywhere: React is not a full-blown framework; it's just a library for rendering views.
How Does the Virtual DOM Work?

The Virtual DOM is at the core of what makes React fast at rendering user interface elements and their changes. Let's look closer into its mechanism.

The HTML Document Object Model or DOM is a

programming interface for HTML and XML documents. … The DOM provides a representation of the document as a structured group of nodes and objects that have properties and methods. Essentially, it connects web pages to scripts or programming languages. — MDN

Whenever you want to change any part of a web page programmatically, you need to modify the DOM. Depending on the complexity and size of the document, traversing the DOM and updating it could take longer than users might be prepared to accept, especially if you take into account the work browsers need to do when something in the DOM changes. In fact, every time the DOM gets updated, browsers need to recalculate the CSS and carry out layout and repaint operations on the web page.

React enables developers to make changes to the web page without having to deal directly with the DOM. This is done via the Virtual DOM.

The Virtual DOM is a lightweight, abstract model of the DOM. React uses the render method to create a node tree from React components and updates this tree in response to changes in the data model resulting from actions.

Each time there are changes to the underlying data in a React app, React creates a new Virtual DOM representation of the user interface.

Updating UI Changes with the Virtual DOM

When it comes to updating the browser’s DOM, React roughly follows the steps below:

  • Whenever something changes, React re-renders the entire UI in a Virtual DOM representation.
  • React then calculates the difference between the previous Virtual DOM representation and the new one.
  • Finally, React patches up the real DOM with what has actually changed. If nothing has changed, React won't be dealing with the HTML DOM at all.

One would think that such a process, which involves keeping two representations of the Virtual DOM in memory and comparing them, could be slower than dealing directly with the actual DOM. This is where efficient diff algorithms, batching DOM read/write operations, and limiting DOM changes to the bare minimum necessary, make using React and its Virtual DOM a great choice for building performant apps.

Continue reading %How to Tell if React is the Best Fit for Your Next Project%

Rapid Development of Zend Expressive Modules

SitePoint - Mon, 09/04/2017 - 12:00

I have learned a few tricks when writing Zend Expressive modules that I want to share with you.

Please follow the previous post first to set up a proper working environment. I explained how to install and configure Zend Expressive with Doctrine, Gulp, and an abstract reflection factory - it'll take a total of 10 minutes.

In this tutorial, we'll build a simple read-only blog module (a page listing blog posts from a database) in minutes, demonstrating the kind of rapid development one is capable of with Zend Expressive.

Module Setup

Run this command from your expressive app to get started:

./vendor/bin/expressive module:create Blog

This will generate some base code for a Blog module and will register your module automatically with your application. It will also register your module with the Composer autoloader.

Doctrine Entity and Database Table

Let's make our Blog entity and database tables. First, we need to let our application know that this module provides Doctrine entities.

Open src/Blog/src/ConfigProvider.php and add the following:

public function __invoke() { return [ 'dependencies' => $this->getDependencies(), 'doctrine' => $this->getDoctrine(), 'templates' => $this->getTemplates(), ]; } /** * @return array */ public function getDoctrine(): array { return [ 'driver' => [ 'orm_default' => [ 'drivers' => [ 'Blog\Entity' => 'blog_entity', ], ], 'blog_entity' => [ 'class' => \Doctrine\ORM\Mapping\Driver\SimplifiedYamlDriver::class, 'cache' => 'array', 'paths' => [ dirname(__DIR__) . '/config/doctrine' => 'Blog\Entity', ], ], ], ]; }

Create a blog post entity config at src/Blog/config/doctrine/BlogPost.orm.yml:

--- Blog\Entity\BlogPost: type: entity table: blog_post id: id: type: integer generator: strategy: AUTO fields: title: type: string length: 255 content: type: string length: 16777215

Then, run ./vendor/bin/doctrine orm:generate-entities src.

Continue reading %Rapid Development of Zend Expressive Modules%

Why Developers Should Consider WordPress.com Hosting

SitePoint - Mon, 09/04/2017 - 11:00

What if you could forget about updates, security patches, latency glitches, and bandwidth/disk space issues? Automattic, the company behind WordPress, has provided a hosting service so comprehensive that it even allows installation of third-party plugins and templates.

WordPress (WP) is not only the most popular content management system, but as of August 2017 it powers 28.5% of all of the web (see "Usage Statistics and Market Share of Content Management Systems for Websites"). This is largely because site owners are running a copy of the free software provided at WordPress.org (WP.org) on their own servers.

Hosting your own copy of WP gives you the freedom add plugins, tweak templates and customize the behavior of the software, but it does have downsides such as dealing with lots of updates, security problems, and issues we'll discuss in a moment.

WP also offers a hosted version of its software at WordPress.com. Developers have tended to avoid this option, mainly because it offers considerably less control over customization, no custom templates and no plugins. But at the same time there are advantages, such as automatic updates, much tighter security, and global distribution. And more recently, WP.com has addressed some of its limitations and started offering a lot more control over the ways in which you can customize the software --- even letting you install add-ons.

In this article, we’ll look at what you can and can’t do with a WP.com site, and I’ll offer reasons to why you might reconsider WP.com over the self-hosting option.

WordPress.com: SaaS!

SaaS stands for Software as a Service. Essentially, the software itself --- in this case, WordPress --- is the service. And with the software also comes all of of the infrastructure that's needed to run it, and you don't need to worry about server resources and all of what's needed to run and manage a WP installation.

WP.com is the official hosting supported by Automattic, the company that handed the WordPress trademark to the WordPress Foundation in 2010. Matt Mullenweg, the creator of WP, is the CEO and founder of Automattic, the company for all things WordPress. This is WP in the cloud.

What you get for using a service like WP.com is the peace of mind that things won't get broken even of you leave them entirely unattended. But let's see in detail how switching out from a shared hosting plan to WP.com can simplify things.

Updates and upgrades

When running your own, self-hosted copy of WP, you need to perform regular updates in order to keep your installation safe. The engineering team at WP made the process really smooth, so if you have set certain writing permissions right, this is something that shouldn’t take you more than a minute or two. Still, you’ll need to do that on a somewhat regular basis. A lot of sites get out of date quickly, providing a lot of scope for hackers to get busy.

Then you have the upgrades. Consider these scenarios:

  • an update going from, let's say, version 4.8 to 4.8.1
  • an upgrade from 4.7 to 4.8
  • a mayor upgrade going from version 3.9 to 4.0.

The first, "update" type is normally smooth, with just security and performance issues are involved.

Upgrades can sometimes be problematic, since new features are introduced.

But major upgrades are almost guaranteed to be a pain, with templates and plugins needing to be rewritten in order to work properly with the upgraded API.

Since WP.com is run by the same folks who maintain the WP.org codebase, all of the updates and upgrades are smoothly synchronized from one to the next.

Load balancing and global distribution

Performance matters today more than ever. With developers under pressure to deliver sites fast, it’s not enough to throw a site on shared hosting and leave it at that. Issues like load balancing, and CDNs to deliver content globally immediately, have become a big consideration when setting up a site.

If your sites have an international audience, you'll always have the visitors near to the data center accessing your site very fast, but the more you get away from it, the less responsive your sites will become (e.g: having a site hosted on the US West Cost, and accessing it from Europe.)

WP.com provides load balancing out of the box. No matter now big your site, no matter how much traffic it has, or globally distributed your audience is, WP.com can handle all of it, and more. And it also comes with the benefits of what a cloud hosting service is (see "A Comparison of Shared and Cloud Hosting, and How to Choose"), including being part of a network distributed across the globe, which makes your site nearly instantly available, no matter if accessed from Shanghai, Rome, Johannesburg, New York City, or Rio de Janeiro.

Server upgrades and maintenance

And the same goes with the software that WP relies to run --- PHP and MySQL. Every once in a while, your hosting company will go through a mayor upgrade, with plenty of notification emails, documentation and tutorials on how to make the transition, setting the company's forums on fire. Again, server upgrades don't happen often, but when they do it's a time consuming process that involves things various things up again, testing, and the risk of getting your sites broken if you failed to do transition properly.

If you have a couple of WP installations, the maintenance time will add up, and you'll need to be very methodical to avoid problems in the mid and long run. And the more diverse your clientele, the more servers you'll need to keep an eye on, and the less you'll be able to simplify updates.

WP.com engineers maintain all of the infrastructure for you, and even mayor upgrades (both software and hardware) are handled smoothly. This is the magic of SaaS, where the software itself is the service, and you don't need to worry about anything else other than just using it.

Because of the best DevOps practices, you won't ever find out that such mayor changes happened to the infrastructure. And this won't affect your site's uptime, which will be 100% even during mayor software and hardware upgrades.

Security

A problem of not performing updates in time is that you'll end up with an insecure WP installation where any script kiddie can take control over your sites, by just scanning vulnerable WP versions on the web.

Also, even if your self-hosted WP instance is up to date, it only takes an unattended vulnerability on the server for a more skilled cracker to take over. And while this doesn't happen all the time, it's something many of us have painfully experienced.

Every patch is applied to WP.com as soon as it comes available to WP.org. Also, because of the globally distributed nature of the cloud, the impact of DDoS attacks is heavily minimized. And even in the event of a zero-day exploit being used on WP.com to compromise its websites, as soon as the attack is detected the engineers will immediately reverse the bogus changes and patch the security hole.

Already on a Dedicated Server or Managed Plan? Think Again!

A dedicated server is the power version of a shared hosting plan, or should I say, a "shared hosting plan" without the "shared" part.

Effectively, you'll have more "dedicated" resources, such as bandwidth, CPU, RAM memory, disk space. But in essence, you're still not solving any of the problems described above, so in this sense a dedicated server offers little added value.

And you'll pay a lot for it! The long-term costs of having a dedicated server can be around a $1000/yr. And with just three dedicated servers running a couple of WP sites, you can very easily reach the $500/mo mark.

Turns out that a more cost-effective solution is available, that will not only assign you as much bandwidth, CPU, RAM and space as you can possibly need, but it will also solve all of the above mentioned issues at the same time.

Continue reading %Why Developers Should Consider WordPress.com Hosting%

Learning JavaScript: 9 Common Mistakes That Are Holding You Back

SitePoint - Thu, 08/31/2017 - 16:00

A lot of people try to learn JavaScript and then give up. Then they tell themselves things like, "JavaScript is too confusing," or worse, "Maybe I'm not cut out for web development."

The sad part? There was no need to give up. All that was needed was a different learning approach.

In this article, we'll cover some of the most common learning mistakes people make and find out how to avoid them. Many of these tips will be applicable outside of JavaScript or even web development, so there's that bonus too.

Let's dive in!

Mistake #1: Overanalyzing Instead of Getting Started

It can be tempting to look for all the information you can get before you start learning JavaScript. If you look, you'll find information about how JavaScript is the best thing ever or the worst thing ever, or that you need to be on this framework or that framework. You might also hear that you need to write JavaScript a certain way or else you'll never be a "real" developer.

Whether or not these points have validity, nothing is worse than the six months to a year you'll waste agonizing instead of starting.

Just type one line of code. It doesn't have to be perfect. It can be terrible. If you get started, you've already passed one of the hurdles that stop a lot of people.

Mistake #2: Learning a Framework Before Learning Plain JavaScript

JavaScript frameworks are built on top of vanilla JavaScript, so if you understand JavaScript, you automatically understand the fundamentals of how to use any JavaScript framework.

However, if you jump straight into a framework, you'll end up memorizing without understanding. It's like trying to write sentences without knowing what words mean. You'll end up memorizing random phrases instead of understanding how words work and how to put them together to make your own sentences.

If you go straight to a framework it'll be harder to learn and you'll have a harder time adapting to another framework if you need to. If you learn plain JavaScript first, you have a firm basis to understand all the frameworks.

Mistake #3: Moving to the Next Step Too Soon

One of the most common mistakes is to move on immediately after understanding a concept.

I've definitely struggled with this one because it's tempting to move forwards once you understand something.

What helped was to treat each concept like a new toy; That means taking some time to enjoy what you just learned. Play around, experiment, see if you can do something new with it. You'll learn a lot that way, and you'll remember better as well.

Once you feel like you can apply a concept in your sleep, move on. It takes a little bit more time up front, but soon it makes everything go much faster.

On the other hand, if you rush, you'll end up forgetting and having to backtrack for every little thing. That ends up taking way more time, and it can be discouraging. In fact, this is a common reason people have said they quit JavaScript.

Mistake #4: Not Breaking Concepts Into Small Enough Pieces

Learning is like a staircase: If you can take one step, you can keep taking more steps until you reach your goals. When something is tough to understand, it's often because you're trying to take a flying leap instead of going one step at a time. Of course, it seems impossible!

Continue reading %Learning JavaScript: 9 Common Mistakes That Are Holding You Back%

How to Create CSS Conic Gradients for Pie Charts and More

SitePoint - Wed, 08/30/2017 - 14:00

More and more websites use gradients in one way or another. Some websites use them for navigation components, while others use them in elements like buttons, or with images to create some nice effects.

All browsers have had support for basic CSS linear and radial gradients for a long time now. The CSS Gradients: A Syntax Crash Course article on SitePoint gives you a quick summary of the syntax required to create linear and radial gradients, as well as how to use repeating gradients to create some basic patterns, which is great if you care about web performance and try to avoid using images whenever possible.

After linear and radial gradients, browsers are now slowly starting to support conic gradients, which were first championed by Lea Verou.

In this article, you will learn about the syntax, uses, and browser support for simple conic gradients and repeating conic gradients.

What are Conic Gradients?

Conic and radial gradients are similar in the sense that both of them start from a specified or default point as the center of the circle used to draw them. The difference between the two is that, in the case of radial gradients the color-stops are placed along the radial line, while in the case of conic gradients the color stops are placed along the circumference of the circle.

The position of color-stops for a conic gradient can be specified either in terms of percentage or in terms of degrees. A value of 0% or 0deg refers to the top of the conic gradient. The values keep increasing gradually as you move clockwise. A value of 360deg is equivalent to 0deg. Any color whose color-stop value is greater than 100% or 360deg won't be drawn on the conic gradient but it will still affect its color distribution.

The following image shows a conic gradient that starts with a yellow color and ends with orange.

It is hard not to notice the sharp transition that separates the orange at 360deg from the yellow at 0deg. Remember that conic gradients always produce this transition whenever the starting and ending colors of the conic gradient are very different. One way to avoid it is setting the starting and ending color to the same value.

Syntax for Conic Gradients

Continue reading %How to Create CSS Conic Gradients for Pie Charts and More%

Subscribe to Kariann Wolf Morris aggregator - Web Design &amp;amp; Development
KARIANN WOLF MORRIS
46 Old Stage Road
Ballston Lake NY 12019
p | 518.857.3359