04. April 2016

WebBlock.js

WebBlock.js (GitHub: richardanaya/webblock, License: MIT, npm: webblock)

Web components are a very powerful way to modularize your the UI of your application in a way that is compliant with the standards. One of the problems with this is that Polymer JS is the leading library for web components, because:

  • It has a very steep learning curve
  • It lacks concise ways to write expressions

Luckily did Richard Anaya notice these problems and saw an opportunity to create a library that allows you to get started with Web components quickly and reuse popular virtual DOM technologies like React.

Not only is it compatible with React and VirtualDOM but you can still use indirection data architectures like Flux and Redux. The developer has posted a Redux example in this WebpackBin.

A quick example of how a component would look using React and WebBlock:

import React from 'react';
import ReactDOM from 'react-dom';
import WebBlock from 'webblock';

WebBlock({
  tag: 'pizza',
  virtualDom: WebBlock.React(React,ReactDOM),
  render() {
        return <div>Hello {this.name}</div>;
    },
  attributes: {
    name: String,
  }
});

WebBlock({
  tag: 'pizza-list',
  virtualDom: WebBlock.React(React, ReactDOM),
  render() {
    if(this.names == undefined) return <div></div>;
    const pizzas = this.names.map((x) => {
      function setName(ref){
        //set the property directly on the DOM node
        ref.name = x;
      }
      return <pizza ref={setName}></pizza>
    })
    return <div>{pizzas}</div>
  },
  attributes: {
    names: Array
  }
});

Which you could use in your HTML like so:

<pizza-list names='["margarita", "salami", "veggie"]'><pizza-list>

Besides making all new components, you could also make use of the great collection of components already created for Polymer. To enable this you will need to force Polymer to use ShadowDOM before it is loaded like so:

<script>
    /* this must run before Polymer is imported */
    window.Polymer = {
      dom: 'shadow',
      lazyRegister: true
    };
</script>

30. March 2016

React Intl

React Intl (GitHub: yahoo/react-intl, License: BSD-3-Clause, npm: react-intl)

A very common problem to solve is internationalization or “i18n”.

Fun fact.
i18n stands of i- eighteen letters -n.

Doing i18n in React or any other modern framework is different from how we used to do this. This also requires newer tools. Luckily the nice people of Yahoo to the rescue with React Intl.

React Intl is a part of FormatJS which is a collection of libraries for internationalization that are focused on formatting numbers, dates, and strings for displaying to people.

One of the features I was missing when I was using i18next was plurarization. I would find myself adding prefixed keys to my translation documents and checking the length and on bases of that show the singular or plural version of that translation.

Now we don’t have to do that anymore, because React Intl takes care of all of that. Let’s take a look on how to get started.

import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { IntlProvider, FormattedNumber, FormattedPlural } from 'react-intl';

class App extends Component {
    constructor(props) {
        super(props);
        this.state = {
            name       : 'Eric',
            unreadCount: 1000,
        };
    }

    render() {
        const { name, unreadCount } = this.state;

        return (
            <p>
                Hello <b>{name}</b>, you have {' '}
                <FormattedNumber value={unreadCount} /> {' '}
                <FormattedPlural value={unreadCount}
                    one="message"
                    other="messages"
                />.
            </p>
        );
    }
}

ReactDOM.render(
    <IntlProvider locale="en">
        <App />
    </IntlProvider>,
    document.getElementById('container')
);

This example would render “Hello Eric, you have 1,000 messages”. As you can see it picks the plural version of the string ‘cause the unreadCount is set to a thousand. When working with multiple languages, there is also the problem of different grammar rules when pluralizing. For instance in Russian there are multiple plural rules:

  • one
  • few
  • many
  • other

While in English only one and other are relevant.

If this library intrigues you head over to the FormatJS website and check all the other capabilities.

24. March 2016

React Helmet

React Helmet (GitHub: nfl/react-helmet, License: MIT, npm: react-helmet)

First if all I’d like to start out with giving you guys an explanation for why I have not being posted as regularly as normal. Me and my girlfriend are currently in the process of buying an apartment. This costs a lot of time and effort to get all the paperwork done in time. Once this is resolved I will be back on the daily posts as usual.

Let’s get on with the show. Maybe you are already familiar with the library/component because it is not exactly new anymore. However when I started asking around about how colleagues and friends of mine solve the problem Helmet is trying to solve, they came up with a few useful and working solutions but non as elegant as Helmet without making something like Helmet yourself.

What it does is give you a component to manage the SEO, share and other meta tags. So you don’t have to put that into your index.html. Let’s assume you have an application which has App as an entry point component like so:

function App(){
  return (<div className="app">
    <SomeComponent />
    <SomeOtherComponent>
      <ChildComponent />
      <SecondChildComponent />
    </SomeOtherComponent>
    //.. etc
  </div>);
}

And you want the title to be set to “My Awesome Application”, you can add Helmet like so:

function App(){
  return (<div className="app">
    <Helmet title="My Awesome Application" />
    <SomeComponent />
    <SomeOtherComponent>
      <ChildComponent />
      <SecondChildComponent />
    </SomeOtherComponent>
    //.. etc
  </div>);
}

There are way to much features to this component than I care to mention here, so if it peaked your interest I suggest you head over to the Github Page and check out all it has to offer.

22. March 2016

Statinamic

statinamic (GitHub: MoOx/statinamic, License: MIT, npm: statinamic)

Statinamic is a static site generator for the modern web. It uses React for it’s views and is very easy to get started with but flexible enough that it does not get in your way.

Currently I’m considering moving from Wintersmith, which I currently use for this site, to Statinamic. Since I want to add some features which would require some more customizations, I would be more comfortable using React to implement that.

During the development process of your static application/website you will have all the benefits of hot loading, compilation errors, runtime errors. To get started you will need to install the module inside of an fresh directory which contains a basic package.json which can be acquired via:

npm init;

Then after installation of the module you can call the CLI from the node_modules folder like so:

./node_modules/.bin/statinamic setup

This will prompt you with some questions about what boilerplate you want inserted. Questions like:

  • Name of your project?
  • Homepage url for your website?
  • Should statinamic generate a CNAME file?

After scaffold is done you still need to install the project dependencies by running:

npm i;

Now you can start developing by running:

npm start;

The basic structure it provides you with looks something like this:

├── README.md
├── content
│   ├── 404.md
│   ├── assets
│   │   └── react.svg
│   └── index.md
├── dist
├── package.json
├── scripts
│   ├── build.js
│   ├── config.js
│   ├── index-client.js
│   ├── webpack.config.babel.js
│   └── webpack.config.client.js
└── web_modules
    ├── Footer
    │   ├── index.css
    │   └── index.js
    ├── Header
    │   ├── index.css
    │   └── index.js
    ├── LayoutContainer
    │   ├── index.css
    │   └── index.js
    ├── app
    │   ├── metadata.js
    │   ├── routes.js
    │   └── store.js
    ├── icons
    │   ├── iconmonstr-github-1.svg
    │   └── iconmonstr-twitter-1.svg
    └── layouts
        ├── Page
        │   └── index.js
        ├── PageError
        │   └── index.js
        └── index.js

17. March 2016

ESBox

esbox (GitHub: callumlocke/esbox, License: MIT, npm: esbox)

esbox is a zero-config REPL for when you wanna run a quick experiment using ESNext(ES6/ES7). In that scenario you do not wanna get bothered with setting up you .babelrc and installing dependancies, you just wanna try out some stuff.

It automatically compiles and re-runs your script every time you save the given file. You can look at it as a JSBin/Webpackbin-like setup within your terminal.

One of the very cool features is ‘Magic imports’ which provides some of the most used packages like lodash, bluebird, react, chalk, chai, express, request and many more.

An example which would work straight out of the box:

import cheerio from 'cheerio';
import fetch from 'isomorphic-fetch';
import { cyan } from 'chalk';

(async () => {
  const result = await fetch('https://www.nytimes.com');
  console.assert(result.ok);

  const $ = cheerio.load(await result.text());

  console.log('The New York Times headlines:');

  $('.story-heading').each((i, element) => {
    console.log(' ', cyan($(element).text().trim()));
  });
})();

You would run this using:

esbox script.js