Innovation rarely happens in a vacuum. It usually starts with an individual brave enough to contribute an idea and a team inspired enough to make it great. This blog provides a forum for all Centrons to contribute ideas, make suggestions, ask questions and inspire others. There are no boundaries. To participate, all you need is the desire to build great products.

ES6 and Internationalization for React Developers

By now, you’ve probably heard of both React and the ECMAScript 2015 (ES6) standard; if you haven’t checked them both out, I heartily encourage you to do so. Along with ES6, the Internationalization Standard also provides a few helpful methods which can cut down your LoC and increase your code clarity.

In this article, I’ll share with you some tips on how to use ES6 and Internationalization features to simplify and enhance your React code. I’ll be assuming that the reader has some working knowledge of both ES6 and React, but you don’t need to be an expert to follow along.

ES6 Functions in a React Context

Let’s say we have the following view:

import React from "react";
import ReactDOM from "react-dom";

const HelloWorldView = React.createClass({
  generateText: function(name, day) {
    var _name = name || "World";
    var _day = day || "day";

    return "Hello, " + _name + "! Today is such a beautiful " + _day + "!";
  },

  render: function() {
    return <div> { this.generateText(this.props.name, this.props.day) } </div>;
  }
});

ReactDOM.render(
  <HelloWorldView name="Dale" day="Monday" />,
  document.getElementById("content")
);

Phew! So much work just to say:

Hello, Dale! Today is such a beautiful Monday!

Without delving deeper into ES6 just yet, we can use React’s Stateless Functions feature to shorten the code while giving us the same results:

const HelloWorldView = function(props) {
  var _name = props.name || "World";
  var _day = props.day || "day";

  return <div>Hello, {_name}! Today is such a beautiful {_day}!</div>;
}

ReactDOM.render(
  <HelloWorldView name="Dale" day="Monday" />,
  document.getElementById("content")
);

That’s certainly shorter! But can we do better?

const HelloWorldView = ({name = "World", day = "day"}) =>
  <div> Hello {name}! Today is such a beautiful {day}! </div>;

ReactDOM.render(
  <HelloWorldView name="Dale" day="Monday" />,
  document.getElementById("content")
);

We’ve used a few ES6 features (namely, Arrow Functions, Destructuring Assignment and Default Parameters) to make our code more concise and more readable at the same time.

An Arrow Function in the form (params) => { console.log("Method body"); }, is the equivalent of a traditional function with a .bind(this). For example, the preceding arrow function in this paragraph would be equivalent to: (function(params){console.log("Method Body");}).bind(this).

The Destructuring Assignment feature intuitively and flexibly breaks down objects and arrays into individual variables that can be referenced directly in the body of the function. For example, we can do the following:

var a,b;
[a,b] = [1,2];
console.log(a); // 1
console.log(b); // 2

({a,b} = {a:1, b:2})
console.log(a); // 1
console.log(b); // 2

Default Parameters help by reducing the need to do null checks or other boilerplate logic at the top of your function blocks. For example:

function bark(loud = false) {
  if (loud) console.log("WOOF!");
  else console.log("woof");
}

bark(); // "woof";
bark(true); // "WOOF!"

Using Internationalization

Note: Internationalization is not supported fully on all browsers. In order to use it with Babel and Webpack, you’ll have to install the appropriate plugin or polyfill.

Let’s say that, in addition to pleasantly greeting the user, we need our code to also politely remind them that they owe us money. We could do this naively, like this:

function writeRequest(amount) {
  return "Btw you owe me $" + amount + "...";
}

const HelloWorldView = ({name = "World", day = "day", amount = 0}) =>
  <div> Hello {name}! Today is such a beautiful {day}! {writeRequest(amount)} </div>;

ReactDOM.render(
  <HelloWorldView name="Dale" day="Monday" amount={9500342.87}/>,
  document.getElementById("content")
);

Which gives us:

Hello Dale! Today is such a beautiful Monday! Btw you owe me $9500342.87...

But that didn’t give us the decimal separators. We could Google a bit and come up with a solution like this:

// taken from http://stackoverflow.com/a/9318724

Number.prototype.formatMoney = function(decPlaces, thouSeparator, decSeparator) {
  var n = this,
          decPlaces = isNaN(decPlaces = Math.abs(decPlaces)) ? 2 : decPlaces,
          decSeparator = decSeparator == undefined ? "." : decSeparator,
          thouSeparator = thouSeparator == undefined ? "," : thouSeparator,
          sign = n < 0 ? "-" : "",
          i = parseInt(n = Math.abs(+n || 0).toFixed(decPlaces)) + "",
          j = (j = i.length) > 3 ? j % 3 : 0;
  return sign + (j ? i.substr(0, j) + thouSeparator : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thouSeparator) + (decPlaces ? decSeparator + Math.abs(n - i).toFixed(decPlaces).slice(2) : "");
};

var myMoney=3543.75873;
var formattedMoney = '$' + myMoney.formatMoney(2,',','.'); // "$3,543.76"

But instead of forcing us to use unmaintainable code snippets like this one, ES6 features native internationalization formatters that will format not only currency, but also numbers, dates and times. This helps a lot in React contexts:

const USD = new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" });

function writeRequest(amount) {
  return `Btw you owe me ${USD.format(amount)}...`;
}

Which renders:

Hello Dale! Today is such a beautiful Monday! Btw you owe me $9,500,342.87...

It’s also super neat because we’re using ES6 Template Strings to avoid nasty string concatenation. As a plus, it’s really easy to switch out the Internationalization code "en-US" and replace it with other countries’ codes, maybe in a config file somewhere.

I hope you have found this article useful and informative. As you can see, there are a lot of features that are present in ES6 that make life easier for React developers. For more reference material, and to learn more about ES6, you can visit the following pages: