Monthly Archives: October 2016

The Vital Guide to React.js Interviewing


Intro

Another wave of evolution in client-side application development is approaching. It involves ES6, the new version of JavaScript, universal applications, functional programming, server-side rendering and a webpack, which is like a task-runner with a jetpack.

Also, React is super hot right now. It is a concise and excellent framework to build performant components. Since we already have all that, how do you find the missing piece — the engineer who will embrace it and build state-of-the-art software for you?

React revolutionized the way we think about apps

React revolutionized the way we think about apps

React Plainly

First things first. In the context of React being marketed as only a views library, and as client-side applications consist of more than just views, React won’t be the only tool that your candidate will use. Still, it is a crucial one. Here are a few screening questions.

Q: What are higher-order components in React?

Broadly speaking, a higher-order component is a wrapper. It is a function which takes a component as its argument and returns a new one. It can be used to extend or modify the behaviour (including the rendered output) of the contained component. Such use of components that change behavior without modifying the underlying class in React is well characterized by the decorator pattern.

The higher-order components are a way to build components using composition. An example use case would be to abstract out pieces of code, which are common to multiple components:

Player.js

import React, {Component, PropTypes} from 'react';

export default class Player extends Component {
  static propTypes = {
    black: PropTypes.bool,
    data: PropTypes.object,
    styles: PropTypes.object
  };

  static defaultProps = {
    black: false,
    data: {
      src: null,
      caption: ''
    },
    styles: {}
  };

  render() {
    const { black, data, styles } = this.props.data;
    return (
      <div className={
        'module-wrapper' +
        (styles ? ' ' + styles : '') +
        (black ? ' module-black' : '')}>
        <section className="player-wrapper video-player-wrapper">
          <video className="player" src={data.src} />
          <p className="player-caption">{data.caption}</p>
        </section>
      </div>
    );
  }
}

Consider this component, which holds a Player but also contains module markup. That markup could be reused for other components. Let’s abstract it, and also allow for passthrough of properties:

Player.js

import React, {Component, PropTypes} from 'react';
import ModuleContainer from './ModuleContainer';

export class PlayerInline extends Component {
  static propTypes = {
    data: PropTypes.object
  };

  static defaultProps = {
    data: {
      src: null,
      caption: ''
    }
  };

  render() {
    const { src, caption } = this.props.data;
    return (
      <section className="player-wrapper video-player-wrapper">
        <video className="player" src={src} />
        <p className="player-caption">{caption}</p>
      </section>
    );
  }
}

const Player = new ModuleContainer(Player);
export default Player;

ModuleContainer.js

import React, {Component, PropTypes} from 'react';

export default function ModuleContainer(Module) {
  return class extends Component {
    static propTypes = {
      black: PropTypes.bool,
      styles: PropTypes.object
    };

    render() {
      const { black, styles } = this.props // eslint-disable-lint
      return (
        <div className={
          'module-wrapper' +
          (styles ? ' ' + styles : '') +
          (black ? ' module-black' : '')
        }>
          <Module {...this.props} />
        </div>
      );
    }
  };
}

Now we can still use the previous way of instantiating Player, no changes here. We can also use the inline player if we prefer. Then the module wrapper markup and props can be used with other modules:

<Player data={playerData} styles={moduleStyles} />

<PlayerInline data={playerData} />

Higher order components are the immediate answer to the design decision of moving away from mix-ins in React for ES6, which was done in early 2015. In fact, higher-order components make for a clearer structure, and they are easier to maintain because they are hierarchical, whereas mix-ins have a bigger chance of conflicting due to a flat structure.

To learn more, check out another example use case of higher order components, with a focus on messaging props. Also check the introduction to the preference of higher-order components over mixins, outlined by Dan Abramov, the author of Redux, and an interesting example of advanced composition using refs by Ben Nadel.

Q: Which components should rely on state, and why?

Having separation of concerns in mind, it seems wise to decouple the presentation from the logic. In the React world, everything is a component. But the components used to present data should not have to obtain that data from an API. The convention is to have presentational (dumb) components stateless, and container components that rely on the state.

That said, the convention is not strict. There is also more than one type of state in React. Despite varying opinions, utilising local state in presentational and especially interactive components does not seem to be a bad practice.

Another distinction is between component classes and stateless function components. Obviously, the latter does not have a state. Speaking of the stateless function components, it is an official recommendation to use them when possible.

Q: What is JSX? How does it work, and why would you use it?

JSX is syntactic sugar for React JavaScript, which makes it easy to write components because it has XML-like syntax. However, JSX is JavaScript and not HTML, and React transforms the JSX syntax to pure JavaScript.

It looks awkward at first sight, although many developers are used to it by now. The main reason to use it is simplicity. Defining even mildly complex structures which will eventually be rendered into HTML can be daunting and repetitive:

React.createElement('ul', { className: 'my-list' }, 
  React.createElement('li', { className: 'list-element' }, 
    React.createElement('a', { className: 'list-anchor', href: 'http://google.com' }, 'Toptal.com'),
    React.createElement('span', { className: 'list-text' }, ' Welcome to the network')
  ),
  React.createElement('li', { className: 'list-element' }, 
    React.createElement('div', { className: 'list-item-content' }, 
      React.createElement(SomeCustomElement, {data: elementData})
    )
  )
);

Versus:

<ul className="my-list">
  <li className="list-element">
    <a className="list-anchor" href="http://toptal.com">Toptal.com</a>
    <span className="link-text"> Welcome to the network</span>
  </li>
  <li className="list-element">
    <div className="list-item-content">
      <SomeCustomElement data={elementData} />
    </div>
  </li>
</ul>

Consider more complex elements navigation components, with multiple nestings. Conciseness is one reason most frameworks have some template engine, and React has JSX.

To learn more, check influential discussion on JSX in the context of container components.

The New Approach to Front-End Development

ES6 (ECMA Script 2015), the new version of JavaScript, was released some time ago. The majority of React materials in the open-source community utilise ES6, and sometimes even ES7. The new version adds in expressiveness to JavaScript and also fixes a few problems of the language. The current standard procedure is to use Babel, which compiles ES6 to ES5. It allows us to write code in ES6, and let it execute correctly on the majority of current browsers as ES5. Therefore, it is crucial that the developer you will hire is proficient with ES6.

Q: What are the new features for functions in ES6?

There are a few, actually. The most prominent is the arrow function expression, which is a concise way of writing anonymous function expressions:

var counterArrow = counter => counter++;
// equivalent to function (counter) { return counter++; }

There is a significant difference. With arrow functions, the this object captures the value of the enclosing scope. So there is no more need to write var that = this.

Another difference is in the way arguments can be defined or passed in. ES6 brings default parameters and rest parameters. Default parameters are a very useful way to set the default value of a parameter when it is not provided in the call. The rest parameters, which have a similar syntax to the spread operator, allow processing an indefinite number of arguments passed to a function in an elegant manner.

var businessLogic = (product, price = 1, ...rest) => {
  product.price = price;
  product.details = rest.map(detail => detail);
};

Q: What are classes in ES6 and React?

ES6 classes provide means to create objects, and actually still rely on prototypal inheritance. They are mostly syntactical sugar, but very handy. However, they are not required for React classes.

React classes are components. They can be defined in one of three ways: using the React.createClass()method, using an ES6 class, or using a function to create stateless function components:

const Counter1 = React.createClass({
  propTypes: {
    count: PropTypes.number
  }

  defaultProps: {
    count: 0
  }

  render: function() {
    return <span>Count: {this.props.count}</span>;
  }
});
class Counter2 extends Component {
  static propTypes = {
    count: PropTypes.number
  }

  static defaultProps = {
    count: 0
  }

  render() {
    return <span>Count: {this.props.count}</span>;
  }
}
function Counter3(props) {
  return <span>Count: {props.count}</span>;
}

Counter3.propTypes = {
  count: PropTypes.number
};

Counter3.defaultProps = {
  count: 0
};

As we previously stated, stateless function components are recommended to use when possible. However, those components are not yet optimised for performance. Consider following GitHub issues in Redux and React to learn more.

Q: What are local, or inline styles, the new trend for styles in web development?

This one is pretty rad. Until now, the declarative CSS always shared a global scope. To add styles to a reusable component, the developer had to choose a namespace carefully. Another thing, sometimes it is hard to work with CSS, because some style had to be computed, and so that single style became an exception. Of course, there is calc(), but it is not always sufficient.

Local styles, sometimes also called referred to as inline styles, solve both these problems. Now it is possible to bind a stylesheet to a component know that they remain local in relation to their scope. The styles will not affect elements out of their scope. If that was not enough, the styles become readily available in JavaScript.

AlertWidget.scss

.alertWidget {
  font-variant: italics;
  border: 1px solid red;
  padding: 13px;
}

.alert {
  font-weight: 700;
  color: red;
}

AlertWidget.js

import React, {PropTypes} from 'react';

function AlertWidget(props) {
  const styles = require('./AlertWidget.scss');
  return (
    

{props.alert}

{props.text}

</div> ); } AlertWidget.propTypes = { alert: PropTypes.text, text: PropTypes.text }; export default AlertWidget;

It may not always be the case all styles have to be local, but it certainly is a very powerful tool. To learn more, check influential introduction to local styles on Medium and discussion on the pros and cons of inline styles on CSS-tricks

React revolutionized the way we think about apps

How Do You State

Applications which encompass more than a single component, especially larger applications, can be difficult to maintain using just local component states. It also feels like a bad practice to put anything more than controller-style logic into React. But do not worry, there are already solutions for that.

Q: What is the application state in React, and what governs the state?

The answer is simple – it is an object which represents the current set of data and other properties of the application. The application state differs from the component local state in the way it can be referred to by multiple components.

Another difference is that the application state should not be changed directly. The only place where it can be updated is a store. Stores govern application state, and also define actions which can be dispatched, such as a result of user interactions.

Most React components should not depend on application scope. It is likely the presentational components should have access to pieces of data, but then that data should be provided to them via properties. In React, the convention is to have only the container elements dispatching actions and referring to the application scope.

Q: So, what tools for governing the state in React are out there?

Handling application state in applications built with React is usually done outside of React. Facebook, who brought us React, also introduced the Flux architecture and just enough of its implementation. The Flux part of the client-side application is where front-end business logic takes place.

React is not tightly coupled with Flux. There is also more than one Flux implementation. In fact, there are many, and there are also other very popular ones which are inspired by Flux. The most popular Flux implementations are Facebook Flux, Reflux and Alt.js. There is also Redux, which is based on Flux principles and many people believe improves on Flux.

These libraries will all get the job done. However, a choice needs to be made and it is crucial for the developer to do it consciously. Some reasonable criteria for making the choice:

  • How popular is the repository? Look for GitHub stars and fork count.
  • Is the framework maintained? Check how many commits were done in the last two weeks. Also, read the author’s notes and the open and closed issue counts.
  • What is the state of the documentation? This one is particularly important, team members can be added or changed but the codebase of your software needs to be clear.
  • How well does the developer know that particular framework?

At the moment of writing this article, Redux is by far the most popular of the bunch. It was also reviewed by the authors of Flux, who agreed that it was excellent work. The documentation is excellent, and there are 30 free short video tutorial lessons by the author. The framework itself is very simple, and most aligned with functional programming paradigms.

Alt.js also has a vibrant community, is highly praised in numerous articles, and has excellent documentation. Alt.js is also a pure Flux implementation. Several other implementations were dropped in favour of the two mentioned.

Here’s an article on the different Flux implementations by Dan Abramov, the author of Redux

Q: What is the unidirectional data flow? What benefits does it bring?

The unidirectional data flow constitutes that all changes to the application state are done in the same general way. That flow follows a similar pattern in Flux implementations, as well as in Redux. The pattern starts with an action, which is dispatched and processed by the stores and has the effect of an updated state, which in turn results in updated views.

By following that pattern, applications which govern their state with Flux or Redux are predictable and normalised. Every state version is a result of calling a set of actions. That means that it is now easier to reproduce every user experience by monitoring which actions were dispatched. A useful example is this article about logging and replaying user actions with Flux on Auth0.

It is also extremely helpful when debugging. In fact, one of the most popular frameworks inspired by Flux, Redux, was created as a side effect of creating a new set of developer tools which themselves rely on Flux concepts. There is a speech to it, called “Hot Reloading with Time Travel”, by Dan Abramov.

Miscellaneous

There are many approaches to programming, and also to software engineering in general. The programming paradigms differ far beyond the style. Recently, there are many mentions of functional programming in JavaScript. There are many advantages awaiting for the developers who seek to embrace it.

Q: Explain the functional programming paradigm.

Functional programming is a paradigm, which stresses on:

  • Writing pure functions.
  • Not having a global state.
  • Not mutating data.
  • Composition with higher-order functions.

Pure functions do not produce side-effects, and also are idempotent, meaning they always return the same value when given the same arguments.

Programs which rely on functional programming have two major advantages. They are easy to understand, and also easy to test. In contrast, assigning variables to the global scope, relying on events, and mutating data makes it very easy for the application to become chaotic. From a JavaScript developer’s perspective, I would even say it is overly easy to end up with code which is difficult to understand and prone to errors.

JavaScript is not a strictly functional language. However, with functions as first-class citizens, which means that they can be assigned and passed around just like other types and are composable, it is certainly possible to embrace functional programming for JavaScript developers.

There are many recent articles that praise this style. Still, what seems to be most important are the new tools, which become very popular very quickly. The tools incorporate the key functional programming ideas in various degrees, and include Redux, recent updates to React, and also others like Bacon.js.

Q: How to incline towards functional programming in React?

Primarily, writing React code is mostly focused on writing good JavaScript code. The general way of writing functional programming in JavaScript would be to keep a consistent style of programming, focused on:

  • Writing pure functions.
  • Keeping the functions small.
  • Always returning a value.
  • Composing functions (utilising higher order functions).
  • Never mutating data.
  • Not producing side effects.

There are many tools in JavaScript which are suited for functional programming, among others: .map(), .reduce(), .filter(), .concat. There are also new ES6 features available, like native promises or the …spread operator.

Also, there are available linters, like eslint in particular, combined with linter configurations based on the Airbnb JavaScript and React style guides. There are also other tools, like immutable.js and code patterns like deepFreeze function, which help prevent the data from mutating which is particularly valuable in tests.

React version 0.14 introduced stateless function components, which are a step towards functional programming from object-oriented programming. Those components are minimal, and should be used when possible. Generally, the vast majority of components in React applications should be presentational.

Using Redux is yet another step in functional programming direction. Redux uses function calls, unlike Flux which relies on events. All Redux reducers are also pure functions. Redux never mutates the application state. Instead, the reducers always return a new state.

Q: How to test React applications?

Last but not least comes the developer’s approach to testing. Regression issues are the ultimate source of frustration. Besides allowing the developer and the client to be assured that the application is working as expected, the tests are the remedy for regression issues.

Building a continuous integration or deployment environment in which every pushed commit is automatically tested, and if successful is deployed, has become a standard these days. It is very easy to set up, with free plans on many SaaS. Codeship for example, has good integrations and a free plan. Another good example is Travis CI which delivers a more stable and mature feeling, and is free for open source projects.

There also have to be actual tests to run. Tests are usually written using some framework. Facebook provided a testing framework for React, it is called Jest, and is based on the popular Jasmine. Another industry standard and a more flexible one is Mocha, often combined with the test runner Karma.

React provides another super feature, the TestUtils. Those provide a full quiver of tools, built specifically for testing the components. They create an abstraction instead of inserting the components into an actual page, which allows to compile and test components using unit tests.

To get more insight into testing React applications, you can read on our blog. I also recommend watching the materials available at egghead.io, where there are some series addressing React, and also Flux and Redux, and even a series with a focus on testing React applications.

Conclusion

React brings high performance to client-side apps, and aligns projects which use it in a good position. The library is widely used, and has a vibrant community. Most often, turning to React, also requires the inclusion of other tools to deliver complete apps. Sometimes, it may call for a more general technology upgrade.

Web development is known to evolve at a very fast pace. New tools gain popularity, become valuable and ready to use within months. The innovations encompass more than just the tools, and often span to the code style, application structure and also system architecture. Front-end developers are expected to build reliable software and to optimize the process. The best are open-minded, and state sound arguments with confidence. Toptal engineers are also able lead teams and projects, and introduce new technology for the benefit of the products.

This article originally appeared on Toptal

Tips & Tricks for a Successful Online Portfolio


Our friends at Toptal screen a lot of designers, so over time we have learned what goes into making a captivating and coherent portfolio. Each designer’s portfolio is like an introduction to an individual designer’s skill set and strengths and represents them to future employers, clients and other designers. It shows both past work, but also future direction. There are several things to keep in mind when building a portfolio, so here is the Toptal Guide of tips and common mistakes for portfolio design.

1. Content Comes First

The main use of the portfolio is to present your design work. Thus, the content should inform the layout and composition of the document. Consider what kind of work you have, and how it might be best presented. A UX designer may require a series of animations to describe a set of actions, whereas the visual designer may prefer spreads of full images.

The portfolio design itself is an opportunity to display your experiences and skills. However, excessive graphic flourishes shouldn’t impede the legibility of the content. Instead, consider how the backgrounds of your portfolio can augment or enhance your work. The use of similar colors as the content in the background will enhance the details of your project. Lighter content will stand out against dark backgrounds. Legibility is critical, so ensure that your portfolio can be experienced in any medium, and considers all accessibility issues such as color palettes and readability.

You should approach your portfolio in the same manner you would any project. What is the goal here? Present it in a way that makes sense to viewers who are not essentially visually savvy. Edit out projects that may be unnecessary. Your portfolio should essentially be a taster of what you can do, a preparation for the client of what to expect to see more of in the interview. The more efficiently that you can communicate who you are as a designer, the better.

2. Consider Your Target Audience

A portfolio for a client should likely be different than a portfolio shown to a blog editor, or an art director. Your professional portfolio should always cater to your target audience. Edit it accordingly. If your client needs branding, then focus on your branding work. If your client needs UX Strategy than make sure to showcase your process.

Even from client to client, or project to project your portfolio will need tweaking. If you often float between several design disciplines, as many designers do, it would be useful to curate a print designer portfolio separately from a UX or visual design portfolio.

3. Tell the Stories of Your Projects

As the design industry has evolved, so have our clients, and their appreciation for our expertise and what they hire us to do. Our process is often as interesting and important to share with them, as the final deliverables. Try to tell the story of your product backwards, from final end point through to the early stages of the design process. Share your sketches, your wireframes, your user journeys, user personas, and so on.

Showing your process allows the reader to understand how you think and work through problems. Consider this an additional opportunity to show that you have an efficient and scalable process..

4. Be Professional in Your Presentation

Attention to detail, both in textual and design content are important aspects of any visual presentation, so keep an eye on alignment, image compression, embedded fonts and other elements, as you would any project. The careful treatment of your portfolio should reflect how you will handle your client’s work.

With any presentation, your choice of typeface will impact the impression you give, so do research the meaning behind a font family, and when in doubt, ask your typography savvy friends for advice.

5. Words Are As Important As Work

Any designer should be able to discuss their projects as avidly as they can design them. Therefore your copywriting is essential. True, your work is the main draw of the portfolio – however the text, and how you write about your work can give viewers insight into your portfolio.

Not everyone who sees your work comes from a creative, or visual industry. Thus, the descriptive text that you provide for images is essential. At the earlier stages of a project, where UX is the main focus, often you will need to complement your process with clearly defined content, both visual diagrams, and textual explanation.

Text can also be important for providing the context of the project. Often much of your work is done in the background, so why not present it somehow? What was the brief, how did the project come about?

Avoid These Common Mistakes

The culture of the portfolio networks like Behance or Dribble have cultivated many bad habits and trends in portfolio design. A popular trend is the perspective view of a product on a device. However, these images often do little to effectively represent the project, and hide details and content. Clients need to see what you have worked on before, with the most logical visualisation possible. Showcasing your products in a frontal view, with an “above the fold” approach often makes more sense to the non-visual user. Usually, the best web pages and other digital content are presented with no scrolling required. Avoid sending your website portfolio as one long strip, as this is only appropriate for communicating with developers.

Ensure that you cover the bases on all portfolio formats. Today it is expected for you to have an online presence, however some clients prefer that you send a classic A4 or US letterhead sized PDF. You need to have the content ready for any type of presentation.

Try to use a consistent presentation style and content throughout the projects in your portfolio. Differentiate each project with simple solutions like different coloured backgrounds, or textures, yet within the same language.

Source: Toptal

Build Ultra-Modern Web Apps with Angular Material


At the Google I/O Conference back in 2014, Google announced Material Design, their new design language. They have since converted much of their popular applications to adhere to this new spec in an effort to provide a consistent experience. Now they are trying to convince you to follow along as well.

Angular Material: Superheroic Javascript Framework Meets Ultra-Modern Design

What is Material Design?

After a visit to the official Material Design spec, you will immediately get a feeling of ultra-modern minimalism. Basic shapes and flat colors are the theme here. Going through the documentation is quite an experience. I recommend taking a look for yourself, but I will summarize it here.

Goal

The purpose is to create a visual language that synthesizes classic principles of good design with the innovation and possibility of technology and science. Also to develop a single underlying system that allows for a unified experience across various platforms and device sizes.

Principles

Material Design is founded on three principles.

Material Is the Metaphor

Inspired by the study of paper and ink, the material lives in 3D space and is grounded in tactile reality. It gives the illusion of space by using realistic shadows. The paper material must abide by the laws of physics (i.e. two pieces of paper may not travel through each other), but may supercede the physical world (i.e. a paper may grow or shrink).

Bold, Graphic, Intentional

Deliberate color choices, edge-to-edge imagery, large-scale typography, and intentional white space create a bold and graphic interface that immerse the user in the experience. The Floating Action Button, or FAB, is a prime example of this principle. Have you noticed that little circle with the ‘plus’ symbol floating around in your Google Inbox app? Material Design makes it very apparent that this is an important button.

Motion Provides Meaning

Motion is meaningful and appropriate, serving to focus attention and maintain continuity. Feedback is subtle yet clear. Transitions are efficient yet coherent. The main point here is to animate only when it has a purpose and not to overdo it.

How does AngularJS fit into Material Design?

AngularJS, Google’s “Superheroic JavaScript MVW Framework”, addresses many of the challenges encountered in developing single-page applications (SPA). It provides the framework needed for creating modern web applications that connect to APIs and never need the page to be refreshed.

AngularJS: A New Approach

Angular is what HTML would have been, had it been designed for applications. HTML is a great declarative language for static documents, but creating dynamic applications not so much.

Creating dynamic applications with HTML has always been an exercise in tricking the browser into doing things it wasn’t meant to do. There are a couple of approaches to doing this.

  1. Library – a collection of functions. (jQuery)
  2. Framework – code dynamically fills in static elements when needed. (Durandal, Ember)

Angular takes a different approach to solve this problem. Instead of struggling with the HTML it is given, it creates new HTML constructs. Angular teaches the browser new HTML syntax through a construct called ‘directives’. Angular comes with a set of these directives built-in, but also allows you to create custom directives, so it allows you to write your own HTML elements.

Wouldn’t it be neat if Google created a set of directives based on Material Design principles?

Introducing Angular Material

Google is actively developing Angular Material, an implementation of Material Design in AngularJS. Angular Material provides a set of reusable UI components based on the Material Design system. Angular Material is composed of several pieces. It has a CSS library for typography and other elements, it provides an interesting JavaScript approach for theming, and its responsive layout uses a flex grid. But the most appealing feature of Angular Material is its amazing collection of directives.

Getting Started

I have created an open source project to help jumpstart your next Angular Material project. The purpose of this project is to give an example of everything Angular Material has to offer, all under one roof. Navigation, paging, theming, and the entire collection of directives are ready to go, all you have to do is feed in your data and bind it to the HTML.

Take a look at the demo here or fork the code on GitHub.

Directives

Directives are a core Angular feature. Angular comes with several directives that you use all of the time like ng-model or ng-repeat. They are a very important piece of Angular that makes the framework function as it should.

How to Use an Angular Material Directive

Angular Material extends this directive library with a set of beautiful Material Design inspired directives. Angular Material directives are HTML tags that begin with ‘md’; short for Material Design. They couldn’t be much easier to use. For example, let’s take a look at the good old button.

A standard HTML button might look something like this.

<button>Click Me</button>

An Angular Material button looks like this.

<md-button>Click Me</md-button>

And this is all that is needed to make a Material button. Now, there are several other options that are available for this directive such as theming it and raising it from the surface to imply importance.

<md-button class="md-raised md-primary md-hue-1">Click Me</md-button>

Services

Services are also core to Angular functionality. They are used to share code across the application. A common core service like $http is used and reused for data calls in Angular applications.

Angular services are:

  1. Lazily instantiated – Angular only instantiates a service when an application component depends on it.
  2. Singletons – Each component dependent on a service gets a reference to the single instance generated by the service factory.

How to Use an Angular Material Service

Angular Material comes packaged with some services that provide some extra functionality to the application. They also contribute to the performance of some of the directives. A great example of a service is the ‘toast’.

A toast is a small notification that slides in from the top of the screen and goes away after a few seconds. Using this service is easy.

In JavaScript,

$mdToast.show(
      $mdToast.simple('Simple Toast!')
        .position('left bottom')
        .hideDelay(3000)
    );

This example shows a simple toast that pops up on the bottom left of the screen and retreats after 3 seconds.

Some services can be personalized with custom templates. In this case, the $mdToast service can use a custom HTML template by using the md-toast directive.

Theming

Material Design is a visual language where themes convey meaning through color, tones, and contrast. These themes are expressed throughout the components in the entire application to provide a more unified feel.

According to the Material Design guidelines, you must “limit your selection of colors by choosing three color hues from the primary palette and one accent color from the secondary palette.” Angular Material makes following this guideline simple by using JavaScript to configure the theme. But first, what is a palette and a hue?

  • Hue: A hue is a single color in a palette.
  • Palette: A palette is a collection of hues.

For example, a palette would be ‘green’ and a hue is a particular shade of green. Angular Material comes packaged with all of the valid palettes from the Material Design spec. You can learn about more about the valid color palettes here.

Theming your project is a piece of cake. In the app.js file, set your desired palettes and hues using the Theming Provider service.

angular.module('myApp', ['ngMaterial'])
.config(function($mdThemingProvider) {
  $mdThemingProvider.theme('default')
    .primaryPalette(‘cyan’, {
      'default': '400',
      'hue-1': '100',
      'hue-2': '600',
      'hue-3': 'A100'
    })
    .accentPalette('amber')
    .warnPalette('red')
    .backgroundPalette('grey');
});

Using the Theme

To apply the theme to the components, set the class of the element to the desired palette and hue.

<md-button class="md-primary">Click me</md-button>
<md-button class="md-primary md-hue-1">Click me</md-button>
<md-button class="md-primary md-hue-2">Click me</md-button>
<md-button class="md-accent">or maybe me</md-button>
<md-button class="md-warn">Careful</md-button>

Layout

Flexbox is the latest and greatest addition to responsive design and Angular Material comes packaged with it. If you are familiar with the Bootstrap grid system, then you should be able to catch on quickly. In fact, Bootstrap is switching to Flexbox in its upcoming release. It has the familiar rows and columns layout you have become accustomed to, but with much more. Learn how to use Flexbox withthis tutorial or study theofficial documentation.

Top 9 Best Angular Material Directives

There are too many Angular Material directives to list them all, so I would like to share with you my favorites.

9. Progress Linear

Often in SPAs, pages need time to load data from the server. If the application shows a blank page during this time, users may think the application is broken and will leave. Let users know the data is loading with theProgress Linear directive. Users will know to wait when they see an animated progress bar indicating that something is happening. Alternatively, use the Progress Circular directive for a round indicator.

8. Date Picker

The Date Picker directive makes choosing a date a clean, simple experience for the user and a true one-liner to write. Simply use md-datepicker and optionally confine the range with md-min-date and md-max-date and that’s it.

7. Autocomplete

Autocomplete provides a pleasant user experience by helping the user choose an option. It is what makes Google’s search engine the best. The Autocomplete directive adds this functionality to your application by completing a user’s words as they type. But the best part about this directive is customization. By filling your autocomplete with md-item-template you can give more meaning to the suggestions. For instance, if a user was searching for names in a company, the autocomplete could show the matching names with their picture and company role, giving a more robust user experience.

6. Bottom Sheet

The bottom sheet is a little menu that slides up from the bottom of your screen, covering content and taking focus. Originally intended to be used solely for mobile devices, the bottom sheet has been gaining popularity on larger screens. To use it, create a template with md-bottom-sheet containing either an md-grid or an md-list for a grid layout or list layout, respectively. Then call it with the Bottom Sheet service, $mdBottomSheet.show().

5. Input

Input forms are boring and have been since the beginning of the internet. But they don’t have to be! Give yourinputs some flair with the Input directive. Wrap your input tag with md-input-container and watch it come to life. Watch as your placeholder animates into a floating label. Easily validate your input with instant, but subtle, color changes and warning messages. Input directive takes an element that is expected to be boring and delivers a pleasant surprise.

4. Toast

The most aggravating user experience is not knowing what the application is doing. We ease this aggravation with toasters, or little unobtrusive notifications. In the olden days, when we sent a request to the server we waited on that page until the response came back before we could move on. User attention span has dropped drastically since then. In today’s SPAs, we click a button and expect to move along immediately, dealing with the server response when it comes. The Toast directive makes this a piece of cake. A toaster is summoned by simply using the Toast Service, $mdToast.show(), and setting the text, duration, and which corner to appear in. Make your own custom toaster with md-toast.

3. Grid List

Are your lists lacking pizazz? Grid lists are an alternative to standard list views. A grid list is best for presenting images, and is optimized for visual comprehension. It works by laying different sized tiles on a grid, giving a scattered, eclectic feel. The tile size and layout then respond to the screen size. This directive is sure to give your application an exciting and fun look.

2. Whiteframe

The concept of space is the core of Material Design and its paper metaphor. Two sheets of paper in the same z-position (or depth), form a seam and must move together. Two overlapping sheets of paper, with different z-positions, form a step. They move independently of each other. To follow the design, we must be able to shift elements along the z-axis. Angular Material provides a simple way to do this. Using the Whiteframe directive, set the class to md-whiteframe-z{x}, where x is the units of depth up from the background. The larger the number, the larger the shadow cast by the paper.

1. Sidenav

Creating a side navigation menu has never been easier. The Sidenav directive places a navigation menu on either the left or right of the screen. Keeping mobile in mind, it swipes in and out as expected, or programmatically with a button click. A nice addition is the lock open feature. The side navigation can be set to lock open when the screen reaches a certain size. By setting the parameter md-is-locked-open=”$mdMedia(‘gt-sm’)” the menu will be tucked away on the phone but locked open on tablet and larger.

Conclusion

Google is converting their most popular applications to Material Design. Now they are heading the development of Angular Material, an implementation of Material Design written in AngularJS. Material Design uses a paper metaphor, bold intentions, and meaningful motion. AngularJS organizes single page applications. Angular Material applies Material Design principles to AngularJS applications.

Material Design is here and Angular Material is a fantastic way to apply the Material design spec to your single page applications. If you want to create your own Angular Material application, don’t waste your time starting from scratch. Rather, start off with a fully functioning app with demos of the directives, theming already set up, and navigation and routing ready to go. Take a look at the demohere or fork the code on GitHub. Of course, you can also learn all about Angular Material by visiting the official documentation.

What do you think about my picks for the best Angular Material directives? Did I get them right? What are your favorites?


This post originally appeared on toptal.com

The 10 Most Common Mistakes That WordPress Developers Make


We are only human, and one of the traits of being a human is that we make mistakes. On the other hand, we are also self-correcting, meaning we tend to learn from our mistakes and hopefully are thereby able to avoid making the same ones twice. A lot of the mistakes I have made in the WordPress realm originate from trying to save time when implementing solutions. However, these would typically rear their heads down the road when issues would crop up as a result of this approach. Making mistakes is inevitable. However, learning from other people’s oversights (and your own of course!) is a road you should proactively take.

WordPress

Engineers look like superheroes, but we’re still human. Learn from us.

Common Mistake #1: Keeping the Debugging Off

Why should I use debugging when my code is working fine? Debugging is a feature built into WordPress that will cause all PHP errors, warnings, and notices (about deprecated functions, etc.) to be displayed. When debugging is turned off, there may be important warnings or notices being generated that we never see, but which might cause issues later if we don’t deal with them in time. We want our code to play nicely with all the other elements of our site. So, when adding any new custom code to WordPress, you should always do your development work with debugging turned on (but make sure to turn it off before deploying the site to production!).

To enable this feature, you’ll need to edit the wp-config.php file in the root directory of your WordPress install. Here is a snippet of a typical file:

// Enable debugging
define('WP_DEBUG', true);

// Log all errors to a text file located at /wp-content/debug.log
define('WP_DEBUG_LOG', true);

// Don’t display error messages write them to the log file /wp-content/debug.log
define('WP_DEBUG_DISPLAY', false);

// Ensure all PHP errors are written to the log file and not displayed on screen
@ini_set('display_errors', 0);

This is not an exhaustive list of configuration options that can be used, but this suggested setup should be sufficient for most debugging needs.

Common Mistake #2: Adding Scripts and Styles Using wp_head Hook

What is wrong with adding the scripts into my header template? WordPress already includes a plethora ofpopular scripts. Still, many developers will add additional scripts using the wp_head hook. This can result in the same script, but a different version, being loaded multiple times.

Enqueuing here comes to the rescue, which is the WordPress friendly way of adding scripts and styles to our website. We use enqueuing to prevent plugin conflicts and handle any dependencies a script might have. This is achieved by using the inbuilt functions wp_enqueue_script or wp_enqueue_style to enqueue scripts and styles respectively. The main difference between the two functions is that with wp_enqueue_script we have an additional parameter that allows us to move the script into the footer of the page.

wp_register_script( $handle, $src, $deps = array(), $ver = false, $in_footer = false )
wp_enqueue_script( $handle, $src = false, $deps = array(), $ver = false, $in_footer = false )

wp_register_style( $handle, $src, $deps = array(), $ver = false, $media = 'all' )
wp_enqueue_style( $handle, $src = false, $deps = array(), $ver = false, $media = 'all' )

If the script is not required to render content above the fold, we can safely move it to the footer to make sure the content above the fold loads quickly. It’s good practice to register the script first before enqueuing it, as this allows others to deregister your script via the handle in their own plugins, without modifying the core code of your plugin. In addition to this, if the handle of a registered script is listed in the array of dependencies of another script that has been enqueued, that script will automatically be loaded prior to loading that highlighted enqueued script.

Common Mistake #3: Avoiding Child Themes and Modifying WordPress Core Files

Always create a child theme if you plan on modifying a theme. Some developers will make changes to the parent theme files only to discover after an upgrade to the theme that their changes have been overwritten and lost forever.

To create a child theme, place a style.css file in a subdirectory of the child theme’s folder, with the following content:

/*
 Theme Name:   Twenty Sixteen Child
 Theme URI:    http://example.com/twenty-fifteen-child/
 Description:  Twenty Fifteen Child Theme
 Author:       John Doe
 Author URI:   http://example.com
 Template:     twentysixteen
 Version:      1.0.0
 License:      GNU General Public License v2 or later
 License URI:  http://www.gnu.org/licenses/gpl-2.0.html
 Tags:         light, dark, two-columns, right-sidebar, responsive-layout, accessibility-ready
 Text Domain:  twenty-sixteen-child
*/

The above example creates a child theme based on the default WordPress theme, Twenty Sixteen. The most important line of this code is the one containing the word “Template” which must match the directory name of the parent theme you are cloning the child from.

The same principles apply to WordPress core files: Don’t take the easy route by modifying the core files. Put in that extra bit of effort by employing WordPress pluggable functions and filters to prevent your changes from being overwritten after a WordPress upgrade. Pluggable functions let you override some core functions, but this method is slowly being phased out and replaced with filters. Filters achieve the same end result and are inserted at the end of WordPress functions to allow their output to be modified. A trick is always to wrap your functions with if ( !function_exists() ) when using pluggable functions since multiple plugins trying to override the same pluggable function without this wrapper will produce a fatal error.

Common Mistake #4: Hardcoding Values

Often it looks quicker to just hardcode a value (such as a URL) somewhere in the code, but the time spent down the road debugging and rectifying issues that arise as a result of this is far greater. By using the corresponding function to generate the desired output dynamically, we greatly simplify subsequent maintenance and debugging of our code. For example, if you migrate your site from a test environment to production with hardcoded URLs, all of a sudden you’ll notice your site it is not working. This is why we should employ functions, like the one listed below, for generating file paths and links:

// Get child theme directory uri
stylesheet_directory_uri();
//  Get parent theme directory
get_template_directory_uri();
// Retrieves url for the current site
 site_url();

Another bad example of hardcoding is when writing custom queries. For example, as a security measure, we change the default WordPress datatable prefix from wp_ to something a little more unique, like wp743_. Our queries will fail if we ever move the WordPress install, as the table prefixes can change between environments. To prevent this from happening, we can reference the table properties of the wpdb class:

global $wpdb;
$user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->users" );

Notice how I am not using the value wp_users for the table name, but instead, I’m letting WordPress work it out. Using these properties for generating the table names will help ensure that we return the correct results.

Common Mistake #5: Not Stopping Your Site From Being Indexed

Why wouldn’t I want search engines to index my site? Indexing is good, right? Well, when building a website, you don’t want search engines to index your site until you have finished building it and have established a permalink structure. Furthermore, if you have a staging server where you test site upgrades, you don’t want search engines like Google indexing these duplicate pages. When there are multiple pieces of indistinguishable content, it is difficult for search engines to decide which version is more relevant to a search query. Search engines will in such cases penalize sites with duplicate content, and your site will suffer in search rankings as a result of this.

As shown below, WordPress Reading Settings has a checkbox that reads “Discourage search engines from indexing this site”, although this does have an important-to-note underneath stating that “It is up to search engines to honor this request”.

WordPress Reading Settings

Bear in mind that search engines often do not honor this request. Therefore, if you want to reliably prevent search engines from indexing your site, edit your .htaccess file and insert the following line:

Header set X-Robots-Tag "noindex, nofollow"

Common Mistake #6: Not Checking if a Plugin is Active

Why should I check if a plugin function exists if my plugin is always switched on? For sure, 99% of the time your plugin will be active. However, what about that 1% of the time when for some reason it has been deactivated? If and when this occurs, your website will probably display some ugly PHP errors. To prevent this, we can check to see if the plugin is active before we call its functions. If the plugin function is being called via the front-end, we need to include the plugin.php library in order to call the function is_plugin_active():

include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
if ( is_plugin_active( 'plugin-folder/plugin-main-file.php' ) ) {
// Run plugin code
}

This technique is usually quite reliable. However, there could be instances where the author has changed the main plugin directory name. A more robust method would be to check for the existence of a class in the plugin:

if( class_exists( ‘WooCommerce’ ) ) {
	// The plugin WooCommerce is turned on
}

Authors are less likely to change the name of a plugin’s class, so I would generally recommend using this method.

Common Mistake #7: Loading Too Many Resources

Why should we be selective in loading plugin resources for pages? There is no valid reason to load styles and scripts for a plugin if that plugin is not used on the page that the user has navigated to. By only loading plugin files when necessary, we can reduce our page loading time, which will result in an improved end user experience. Take, for example, a WooCommerce site, where we only want the plugin to be loaded on our shopping pages. In such a case, we can selectively remove any files from being loaded on all the other sites pages to reduce bloating. We can add the following code to the theme or plugin’s functions.php file:

function load_woo_scripts_styles(){
	
if( function_exists( 'is_woocommerce' ) ){
    // Only load styles/scripts on Woocommerce pages   
	if(! is_woocommerce() && ! is_cart() && ! is_checkout() ) { 		
		
		// Dequeue scripts.
		wp_dequeue_script('woocommerce'); 
		wp_dequeue_script('wc-add-to-cart'); 
		wp_dequeue_script('wc-cart-fragments');
		
		// Dequeue styles.	
		wp_dequeue_style('woocommerce-general'); 
		wp_dequeue_style('woocommerce-layout'); 
		wp_dequeue_style('woocommerce-smallscreen'); 
			
		}
	}	
}

add_action( 'wp_enqueue_scripts', 'load_woo_scripts_styles');

Scripts can be removed with the function wp_dequeue_script($handle) via the handle with which they were registered. Similarly, wp_dequeue_style($handle) will prevent stylesheets from being loaded. However, if this is too challenging for you to implement, you can install the Plugin Organizer that provides the ability to load plugins selectively based on certain criteria, such as a post type or page name. It’s a good idea to disable any caching plugins, like W3Cache, that you may have switched on to stop you from having to refresh the cache constantly to reflect any changes you have made.

Common Mistake #8: Keeping the Admin Bar

Can’t I just leave the WordPress Admin Bar visible for everyone? Well, yes, you could allow your users access to the admin pages. However, these pages very often do not visually integrate with your chosen theme and don’t provide a seamless integration. If you want your site to look professional, you should disable the Admin Bar and provide a front-end account management page of your own:

add_action('after_setup_theme', 'remove_admin_bar');

function remove_admin_bar() {
if (!current_user_can('administrator') && !is_admin()) {
  show_admin_bar(false);
}
}

The above code, when copied into your theme’s functions.php file will only display the Admin Bar for administrators of the site. You can add any of the WordPress user roles or capabilities into the current_user_can($capability) function to exclude users from seeing the admin bar.

Common Mistake #9: Not Utilizing the GetText Filter

I can use CSS or JavaScript to change the label of a button, what’s wrong with that? Well, yes, you can. However, you’re adding superfluous code and extra time to render the button, when you can instead use one of the handiest filters in WordPress, called gettext. In conjunction with a plugin’s textdomain, a unique identifier that ensures WordPress can distinguish between all loaded translations, we can employ the gettextfilter to modify the text before the page is rendered. If you search the source code for the function load_plugin_textdomain($domain), it will give you the domain name we need to override the text in question. Any reputable plugin will ensure that the textdomain for a plugin is set on initialization of the plugin. If it’s some text in a theme that you want to change, search for the load_theme_textdomain($domain) line of code. Using WooCommerce once again as an example, we can change the text that appears for the “Related Products” heading. Insert the following code into your theme’s functions.php file:

function translate_string( $translated_text, $untranslated_text, $domain ) {
	if ( $translated_text == 'Related Products') {
			$translated_text = __( 'Other Great Products', 'woocommerce' );
	}
	return $translated_text;
}

add_filter( 'gettext', 'translate_string', 15, 3 );

This filter hook is applied to the translated text by the internationalization functions __() and _e(), as long as the textdomain is set via the aforementioned functions.

_e( 'Related Products', 'woocommerce' );

Search your plugins for these internationalization functions to see what other strings you can customize.

By default, WordPress uses a query string with the post’s ID to return the specified content. However, this is not user-friendly and users may remove pertinent parts of the URL when copying it. More importantly, these default permalinks do not use a search engine friendly structure. Enabling what we call “pretty” permalinks will ensure our URLs contain relevant keywords from the post title to improve performance in search engine rankings. It can be quite a daunting task having to retrospectively modify your permalinks, especially if your site has been running for a significant period of time, and you’ve got hundreds of posts already indexed by search engines. So after you’ve installed WordPress, ensure you promptly change your permalinks structure to something a little more search engine friendly than just a post ID. I generally use the post name for the majority of sites I build, but you can customize the permalink to whatever format you like using the availablepermalink structure tags.

WordPress Permalink Settings

Conclusion

This article is by no means an exhaustive list of mistakes made by WordPress developers. If there’s one thing you should take away from this article, though, it’s that you should never take shortcuts (and that’s true in any development platform, not just in WordPress!). Time saved now by poor programming practices will come back to haunt you later. Feel free to share with us some mistakes that you have made in the past – and more importantly any lessons learned – by leaving a comment below.

Source: Toptal