JSX preprocessor – A syntax sugar for ReactJS

The JSX preprocessor

JSX preprocessor it is a step that adds XML syntax to JavaScript. You can definitely use React without JSX but JSX makes React a lot more elegant.

When you start typing code, driving yourself into the amazing world of web programming sometimes you may feel overwhelmed when you have to select a tool, a library or a framework as your initial learning point. Out there are too many tools, each one with different features aiming the same goal in their own way. Eventually you realize that HTML and CSS are not enough, you need JavaScript. And now for react you are able to use
JSX preprocessor.

JSX preprocessor

At some point, vanilla JavaScript became too heavy and hard in order to achieve certain task, the most efficient way is to make use of a library or a framework.
This time is the turn for ReactJS, it is a JavaScript library, and specifically one of its many features: JSX. Now, we will assume you already know something about ReactJs and the ecosystem around it. Otherwise you should start here first and then move on to this topic.

ReactJS feature:
Basically JSX is an inline markup that looks like XML/HTML and gets transformed to JavaScript (sometimes it can remind you a template language). It is possible to use ReactJS without JSX but JSX makes ReactJS code more elegant. A JSX expression starts with an XML/HTML-like open tag, and ends with the corresponding closing tag, it also supports the XML syntax so you can optionally leave the closing tag off. See the follow example:

 
const hw = <p>Hello, world!</p>;

This code is just JSX syntax example but you also can do things like embed JavaScript expressions in JSX by wrapping it in curly braces:

 

function hello(text) {
  return text.firstWord + ' ' + text.secondWord + '!';
}

const text = {
  firstWord: 'Hello',
  secondWord: 'World'
};

const element = (
  <p>
    This is a, {hello(text)}!     // embed JavaScript expression 
  </p>
);

Even specify attributes like follow:
You may use quotes to specify string literals as attributes:

 
const element = <div z-index="1"></div>;

You may also use curly braces to embed a JavaScript expression in an attribute:

 

var style = { backgroundImage: 'url(picture.png)', height: 10, width: 15 };
return <div style={style}></div>;

Now let’s analyze an example combined with ReactJS.

ReactJS applying JSX

 
var test = (  
  <div className='test-example'>//notice the parameter className instead of class
    <img 
      src='image.png'
      className='test-example'
    />
  </div>)

ReactDOM.render(test, document.getElementById('myapp'))

As you can see, it is like write HTML/XML code inside JavaScript but at the end it is just JavaScript. The special consideration is that JSX makes you name the attributes in a different way form the standard, in the example above, the ‘class’ for CSS must be named ‘className’ instead of the html standard attribute ‘class’.

Basically JSX produces React “elements” and according to the official documentation ‘JSX just provides syntactic sugar to React.createElement(…) function’, see below:

 

<MyButton color="green" shadowSize={10} >
  Go!
</MyButton>


 
compiles into:
React.createElement(
  MyButton,
  {color: 'green', shadowSize: 10},
  'Go!'
)

JSX preprocessor Pros:

Declarative syntax:
Provides a very easy way to import static HTML or migrate from JavaScript templates. Plus, its enforces good syntactical restrictions similar to XHTML that improves quality of codebase.
ReactJS Documentation priories JSX:
ReactJS documentation uses JSX everywhere so JSX is only going to become more powerful.
Very useful tools and resources:
Babel is a tool able to transpiles ES6, ES7(stage 1 flag), JSX altogether.

Integrations with other frameworks

JSX simple example with AngularJS:
You can integrate JSX preprocessor with Angularjs to write the templates in places that you use javascript, for example in the directives.
If you want to use JSX-style with AngularJS the way is through AngularJS directives. In order to achieve this goal, we have angular-jsx library to convert templates into strings that Angular can understand. Take a look to this example:

Input

 
angular.module("foo").directive("bar",
    function() {
        return {
             // it can be used in the template for the directives
            template: <div>This is a simple example.</div>
        };
    }
);

Output

 
angular.module("foo").directive("bar",
    function() {
        return {
            template: "<div>This is a simple example.</div>"
        };
    }
);

More information about it can be found here. If you want a deeper point of view about more technical aspects related to ReactJs and JSX maybe this article will do the trick for you.

Redux with React – First look

redux with react
This time I going to take the time to research and write about Redux in combination with React, one of the hottest libraries for front-end web development. It was created in 2015, influenced by Flux architecture and became popular very quickly because of it’s simplicity, excellent documentation and size (2 KB). Also is very easy to use redux with react. Let’s start with the basics:

What is Redux?

According to the official site Redux is defined as a predictable state container for JavaScript apps. Basically Redux maintains the state of an entire application in a single immutable state tree (object). This object can’t be changed directly. When something changes, a new object is created (using actions and reducers). The main goal of Redux is to facilitate the task of connect sources of different environments like for example APIs and sockets.

Redux with React.

Redux is kind of ‘created’ to work with React.js but also can be used with Angular.js, Backbone.js or just vanilla JS.

How to install it?

To install the stable release (through npm as package manager with a module builder like Webpack or Browserify to use modules of CommonJS):
npm i -S redux
Also you may want to install the connection to React and the developer tools.
npm i -S react-redux
npm i -D redux-devtools

Core concepts of Redux

1 – Actions.
The actions, summarized actions are events. The action task is to send data from the application (user interactions, internal events such as API calls, and form submissions) to the store. The only way to pass information to the store is through actions. The actions are POJO (Plain Old JavaScript Objects) with at least one property that indicates the action type and, if necessary, others properties indicating any other necessary data to do the action. Normally they use the format defined in FSA.

An action example:

 
{
    type: 'TODO_APP',
    payload: {
        text: 'How to learn Redux,
    },
}

Actions are created with action creators. They are just functions that return actions.

 
function myAction(someText) {

return {
	type: TODO_APP,
	payload: someText
}
}

To call an action anywhere in our app must be through dispatch method, like this:

 
// to send an action to the Store (The concept of Store will be seen ahead).
Store.dispatch (myAction(someText)); 

2 – Reducers.

While the actions describe that ‘something’ happen they don’t specify how our app reacts to that ‘something’. In Redux, reducers are functions (pure, I will explain what a pure function is later) that take the current state of the application and an action and then return a new state.
(prevState, action) => nextState
Here is a very simple reducer that takes the current state and an action as arguments and then returns the next state:

 

function handleAuth(state, action) {
	return _.assign({}, state, {
		auth: action.payload
	});
}

Some things you should never do in a reducer:
Modify the arguments directly (the right way is to create a copy first.)
Do actions with secondary effects like API calls or change a route.

The name we put to the reducer is used as property of ‘store’ we created and is where will be saved the state returned from the reducer.

3 – Store
Store is the object that holds the application state and provides a few helper methods to access the state, dispatch actions and register listeners. The entire state is represented by a single store. Any action returns a new state via reducers.
The store has four main responsibilities:
Store the global state of the app.
Give access to the state through store.getState()
Allow the update of the state through store.dispatch()
Register listeners through store.subscribe(listener)
Take this as example:

 

import { createStore } from 'redux';

	let store = createStore(rootReducer);
	let authInfo = {username: 'alex', password: '123456'};
	store.dispatch(authUser(authInfo));

This image illustrates the work flow of Redux.

redux dataflow
Redux data flow (Image: Tanya Bachuk)

The three principles of Redux.

– Single data source: The app state stores in one objet tree inside a unique STORE.
– The state is read only: The only way of change the state is through ACTIONS.
– Changes are made with pure functions: To specify how the state tree is transformed by actions, you write pure reducers.

Where can Redux be used?

Contrary of what you may be thinking, the only use of Redux isn’t with React. It can be integrated with any other library/framework like for example Vue.js, Polymer, Ember, Backbone.js or Meteor, but Redux plus React, though, is still the most common combination.

Integrating Redux with React: Installing react-redux

The connection of Redux with React isn´t included directly inside Redux, in order to achieve this, we need to download react-redux:
npm i -S react react-dom react-redux redux

Encapsulating the app.

First we need to encapsulate our app with the component Provider that comes with react-redux. This component receives a unique parameter called store which one is the instance of the STORE we are using. See the follow example.

 
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import React from 'react';
import store from './store';
import App from './components/App';

render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('app')
);

This component Provider defines in the global context of React our instance of store.

Accessing the store.

Now is time to define what components are going to Access our Store, because not all of them will need to. In order to do that we need to connect our Redux components to Redux, this can be achieved with a decorator that came with react-redux called connect.

 
// Importing the decorator @connect of react-redux

import { connect } from 'react-redux';
import React from 'react';
import UserItem from './UserItem';

// Aplying the decorator @connect to our component.

@connect()
class UserList extends React.Component {
  render() {
    // Rendering the user list we receive from Store  .  
    return (
      <section>
        {
          this.props.users
            .map(user => <UserItem {...user} key={user.id} />)
        }
      </section>    
    );
  }
}
export default UserList;

This way our component UserList will have inside it props all the data of the Store. With this we can render our app using the data stored in the Redux Store.

Pure functions vs Impure functions:

Pure Functions
A function is considered pure if:
a) It always returns the same value when given the same arguments.
b) It does not modify anything (arguments, state, database, I/O, ..).

Examples of Pure Functions (in JavaScript):

 
function add(x, y) {
return x+y;
}
 
function getLength(array) {
return array.length;
}

Impure Functions

A function is considered impure if it is not pure, typically because:
a) it makes use of an external or random value. (It stops being entirely contained and predictable.)
b) It performs an external operation, in other words it causes side effects.

 
var x = 5;
function addToX(a) {
return a+x; / Use of an external variable
}

Example: A complete reducer with tests (can use a library for this like Expect.js).

You might be interested in:

First look to javascript unit test framework – ExpectJs

 

const counter = (state = 0, action) => {

  switch (action.type) {
    case 'INCREMENT':
      return state + 1;
      
    case 'DECREMENT':
      return state - 1;
      
    default:
      return state;
  }
}

expect(
  counter(0, {type: 'INCREMENT'})
).toEqual(1);

expect(
  counter(1, {type: 'INCREMENT'})
).toEqual(2);

expect(
  counter(2, {type: 'DECREMENT'})
).toEqual(1);

expect(
  counter(1, {type: 'DECREMENT'})
).toEqual(0);

expect(
  counter(1, {type: 'DECREMENT Else'})
).toEqual(1);


expect(
  counter(undefined, {})
).toEqual(0);

console.log('Tests passed!');

Why would I need to use Redux? (extracted from this article)

Predictability of outcome:
There is always one source of truth, the store, with no confusion about how to sync the current state with actions and other parts of the application.
Maintainability:
Having a predictable outcome and strict structure makes the code easier to maintain.
Organization:
Redux is stricter about how code should be organized, which makes code more consistent and easier for a team to work with.
Server rendering:
This is very useful, especially for the initial render, making for a better user experience or search engine optimization. Just pass the store created on the server to the client side.
Developer tools:
Developers can track everything going on in the app in real time, from actions to state changes.
Community and ecosystem:
This is a huge plus whenever you’re learning or using any library or framework. Having a community behind Redux makes it even more appealing to use.
Ease of testing:
The first rule of writing testable code is to write small functions that do only one thing and that are independent. Redux’s code is mostly functions that are just that: small, pure and isolated.
Pure functions:
return a new value based on arguments passed to them. They don’t modify existing objects; instead, they return a new one. These functions don’t rely on the state they’re called from, and they return only one and the same result for any provided argument. For this reason, they are very predictable.
Because pure functions don’t modify any values, they don’t have any impact on the scope or any observable side effects, and that means a developer can focus only on the values that the pure function returns.

CONCLUSION

Redux has a growing popularity and is even bigger every day. Companies like Uber and Twitter and projects like WordPress are using it successfully in production. Redux isn’t a perfect fit for everything but we recommend to check it out. If you are up to it you can deep your knowledge over here, a tutorial from the Redux creator and see this example contains source code of Todo List app using Redux with React.

How to copy to clipboard using JavaScript

It is amazing how modern browsers had evolved, and how powerful they became we got to a point where we don’t need flash anymore.
A time ago the only way to copy to browser’s clipboard was from a button in the app using Flash, but with modern browsers we can achieve copy to clipboard using javascript, without using any plugin. First, let’s set the ground of what the clipboard is…

copy to clipboard using JavaScript

The clipboard is basically a place for storing and retrieving a single piece of cloned data, by data means from a simple string to a whole directory. There can be more than one clipboard present, for example, the “operative system clipboard”, it would be less difficult if all the applications were able/created to use the operative system clipboard, but unfortunately this is not always the case. For example, virtual machines, unless you explicitly turn on a clipboard integration option.
Following the same behavior are the web apps. Web applications runs in a sandbox environment, it restricts access to file system and the system clipboard, for security reasons. This article expose why the system clipboard is a restricted resource.
Fortunately, there ways to bypass those restrictions and gain access to system clipboard using JavaScript. This is post is about show several ways to do it.

Copy to clipboard using JavaScript

Example 1 (vanilla JavaScript):

This solution is a simple one but has some drawback because you must add an <input> or <textarea> element with the text to be copied to the DOM. The command used ‘execCommand’ allows us to execute other commands like cut, copy or paste.

The input or textarea to receive text you want to copy:

 
<input name="exampleClipboard" placeholder="Insert the text you want to copy" value="Example text" tabindex="1" autocomplete="off" maxlength="240" style="width:200px" type="text">
<p>
  <button id="copy">
    Copy text
  </button>
</p>
<p>
Right click paste or Ctr + v after click Copytext button <br/>
<textarea></textarea>
</p>

The function to call:

 

<script>
function copyToClipboard() {
document.querySelector('input').select();
document.execCommand('copy');}
</script>

The button:

 
<button id="howToCopyClipboard" onclick="copyToClipboard()">Copy</button

*You can change the input label for a textarea if you want. Keep in mind that this solution forces you to keep a maybe non desire input or textarea element in your page.

 
Try yourself

Example 2 (vanilla JavaScript):

This is a more elaborated solution where we validate compatibility with browsers. For this solution lets create a function that copies a string to the clipboard, this function must be called from within an event handler such as click. More reference to this method can be found here you can see a practical example here.

 

function copyToClipboard(text) {

if (window.clipboardData && window.clipboardData.setData) {
 // IE specific code path to prevent textarea being shown while dialog is visible.

return clipboardData.setData("Text", text); 

} 

else if (document.queryCommandSupported && document.queryCommandSupported("copy")) {
        var textarea = document.createElement("textarea");
        textarea.textContent = text;
        textarea.style.position = "fixed";  // Prevent scrolling to bottom of page in MS Edge.
        document.body.appendChild(textarea);
        textarea.select();
        try {
            return document.execCommand("copy"); // Security exception may be thrown by some browsers.
        } catch (ex) {
            console.warn("Copy to clipboard failed.", ex);
            return false;
        } finally {
            document.body.removeChild(textarea);
        }
    }
}

Example 3 (with a library): Clipboard js

It would be overwhelm to have to write validations for browser compatibility, etc, so Lets avoid reinvent the wheel and use a library that manages all this for you. ClipboardJs is very easy to use, here is an example:

 
<!-- Target -->

<input id="textToCopy" value="Any text you want to copy">

 

 

<!-- Trigger -->

<button class="btn" data-clipboard-target="#textToCopy">Copy to clipboard
</button>

Notice that

 data-clipboard-target 

do the job here. Let’s see another feature but this time is to cut instead of copy.
The only change needed is to add

 data-clipboard-action="cut"> 

like this:

  
<textarea id="textToCopy">Another feature … </textarea>
  
<!-- Trigger -->
<button class="btn" data-clipboard-action="cut" data-clipboard-target="#textToCopy">
    Cut to clipboard
</button>

More reference about this useful library can be found here.

Try yourself

At the end there isn’t universal solution to this task, out there are a lot of solutions in many different ways with just JavaScript (or JavaScript libraries without involving Flash), feel free to use the most suited for you.

First look to javascript unit test framework – ExpectJs

Today I going to write about javascript unit test frameworks, to be more specific, about Expectjs.
Sometimes web developers ignores the action of testing their code, automated, just because it works in
some random manual attempts. Just a reduced number of developers really like the activity of write unit test because of the security and the mind peace it brings to any development process.
This time let’s take a look at ExpectJS, a minimalistic BDD assertion toolkit based on should.js that
provides very useful features to developers in order to test their codes through unit test. But how it
works exactly? In this post I’d like to expose the main features and APIs of this amassing library.
 
javascript unit test framework

Two definitions before go to the main topic: Assertions + Unit Testing with ExpectJs

Basically an assertion is a statement where a Boolean-valued function is expected to be true at that
point in the code. If the assertion evaluates to false in some point of the execution, it will throw an
assertion exception. For example:

 
function assert(condition, message) {
    if (!condition) {
        throw message || "Assertion failed";
    }
}
 

In the other hand, a unit test checks blocks of code to ensure that they all run as expected. Simple JavaScript unit test will take a function, monitor output and return its behavior, and assertions are used in the process. Sometimes this task is not so easy with vanilla JavaScript.

Other javascript unit test frameworks

There are other options. Out there are plenty of javascript unit test frameworks like QUnit, Sinon, Mocha or Jasmin, all of them are able to integrate assertions libraries like ExpectJS.

Let’s get starting with ExpectJS

How to install it.
 
Node
Install it with NPM or add it to your package.json:
$npm install expect.js
Then you can use the following code:

var expect = require('expect.js');

Browser

<!-- download the file to your local -->
<script src="expect.js"></script>

<!-- from a CDN -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/expect.js/0.2.0/expect.js">
</script>

 

Main features

– Cross-browser: works on IE6+, Firefox, Safari, Chrome, Opera.
– Compatible with all test frameworks.
– Node.JS ready (require(‘expect.js’)).
– Standalone. Single global with no prototype extensions or shims.

Our first test

Let’s say we want to test the following add function:

function add(a, b) {
return a – b; 
};

expect(add).to.be.a('function');  // this assertion passes
expect(add(1, 3)).to.equal(4);  // this assertion fail
expect(add(5, 2)).to.be.lessThan(8); // this assertion passes

Now, notice that if we execute this code, and we check the console of the browser you’ll see an error for the assertion that failed (the second one).

 
Try it yourself

The previous approache is not too intuitive, so lets wrap it up with a framework that offers a more visual result, lets use MochaJs:

Comparing with other assertion test frameworks

Differences with should.js
– No need for static shouldjs methods like should.strictEqual(). For example, expect(obj).to.be(undefined) works well. More intuitive now!
– Some API simplifications/changes.
– API changes related to browser compatibility.

Let’s see how intuitive the ExpectJS API’s can be.

Example 1: a/an: asserts typeof with support for array type and instanceof (used with mocha testing framework)

describe("Example 1", function() {

 var n;
 var cars;

it("number check", function() {
    n = 'good';
    expect(n).to.be.a('number');
  });


  it("array and object check", function() {
    cars =['Mercedes', 'Toyota', '4x4'];
  
   expect(cars).to.be.an('array'); // it works
   expect(cars).to.be.an('object'); // it Works too since it supports typeof
  });
});

Example 2: match: asserts String regular expression match. We can use useful regular expressions like this:

describe("Regular expressions check", function() {
 var version;
it("version check", function() {
    n = '4.8.2';
    expect(version).to.match(/[0-8]+\.[0-8]+\.[0-8]+/);
  });
});

Try it yourself

Other resources the API provides:

ok: asserts that the value is truthy or not.

expect(1).to.be.ok();

eql: asserts loose equality that works with objects.

expect({ a: 'b' }).to.eql({ a: 'b' });

contain: asserts indexOf for an array or string.

expect([1, 2]).to.contain(1);

length: asserts array .length.

expect([]).to.have.length(0);

empty: asserts that an array is empty or not.

expect([]).to.be.empty();

property: asserts presence of an own property (and value optionally).

expect(window).to.have.property('expect')

key/keys: asserts the presence of a key. Supports the only modifier.

expect({ a: 'b' }).to.have.key('a');

throw/throwException/throwError: asserts that the Function throws or not when called.

expect(fn).to.throw(); // synonym of throwException.

withArgs: creates anonymous function to call fn with arguments.

expect(fn).withArgs(invalid, arg).to.throwException();

within: asserts a number within a range.

expect(1).to.be.within(0, 100);

greaterThan/above: asserts.

expect(3).to.be.above(0);

lessThan/below: asserts.

expect(0).to.be.below(3);

fail: explicitly forces failure. (This is very helpful sometimes).

expect().fail()

How to use it with spies.

A way to verify the function behavior in unit test is through the use of spies. A spy allows you to monitor a function exposing options to track invocation counts, arguments and return values. The main principle here is that it replaces a particular function where you want to control its behavior in a test, and record how that function is used during the execution of that test (similar to how actors are replaced with stunt doubles for dangerous action scenes in Hollywood movies).

Let’s see how it works: (Other examples can be found here)

spyOn(foo, 'bar');  // Here the spyOn method takes an object and a method to be spied upon.
foo.bar(1);         // Call the function
 
expect(foo.bar).toHaveBeenCalled(); // Run assertions with ExpectJS.
expect(foo.bar).toHaveBeenCalledWith(1);

Final considerations.

ExpectJS is a very useful assertion library and combined with other javascript unit test frameworks can be very visual and can save a lot of time while provide security to your code. Other libraries similar are Chai, should.js, and better-assert. One of the advantages is that it is Standalone and can be integrated with any javascript unit test frameworks.

References:

https://github.com/Automattic/expect.js/blob/master/README.md
https://abdulapopoola.com/2016/04/11/how-function-spies-work-in-javascript/
https://designmodo.com/test-javascript-unit/