Sunday, May 29, 2016

ReactJS - Introduction

This post is not a tutorial on react. There are bunch of good examples and detail documentation available on react official site. This post is mainly to give very high level introduction on react and will try to explain the very first component i have created.

React is a javascript library, which you can use to create different components. Its component based architecture help structure the project well. There are other libraries also available which gives us facility on creating components, but React has a different algorithm to render these components on browser(generally referred as a virtual DOM), which makes React different from other frameworks.
We can always use react in combination with other js frameworks as well.
Every component in React has a "render" method. One component can be nested within another, and the "render" method is called recursively downwards in the tree. Rendering start with the root component where React.renderComponent is called first.

Virtual DOM -
Render method of every component yield a HTML. React make this generated html part of its internal DOM and then use this internal DOM to create the final HTML DOM on the browser. Whenever there is any change in any component, the internal(virtual) DOM is updated and finally React updates the actual DOM with the final delta.
With this approach of DOM manipulation React is very fast in UI updation.

Flux -
If you are working in React, then you will come across Flux architecture as well. This architecture talks about one way flow(binding) instead of two way. The architecture talks about using dispatcher or callback to handle any update, instead of calling the parent or any other component directly. It says that there should be a single dispatcher class which should dispatch the actions to every component. If any of the component has any update for the application, then it should connect with dispatcher to communicate with other components.

JSX -
React has introduced JSX syntax to make programmer's life easy. We can write our component html structure in JSX format and then
1) we can compile it to standard javascript and include the final file in the html page
2) we can directly include this js file having JSX code in our html and mark it with "text/babel" type and include browser.js also, which will convert this JSX into standard javascript at run time. Ofcourse there will be performance hit because of this.
JSX code -
<div >
        Hello, world.
      </div>

Actual translated code -
React.createElement('div',
        "Hello, world"
      )

Getting Started-
Lets try to write a simple hello world code using react.
In our index.html, include following javascripts -

<script src="lib/react.js"></script>
    <script src="lib/react-dom.js"></script>
    <script src="lib/browser.js"></script>
    <script src="lib/jquery.min.js"></script>

react.js and reactdom.js are required for React framework. I have included browser.js for my jsx to javascript conversion.

lets create a simple div where i can render my React component -
<body>
    <div id="content"></div>
    <script type="text/babel" src="example.js"></script>  
</body>

If you notice, i have included example.js, which has my React code, and the script type i have mentioned is "text/babel". I can always precompile it to actual javascript and use it in my HTML.
There is a package named as "grunt-babel" available, which we can use for this conversion.

Also i have created a div with id=content which i ll use to render my component.
Lets have a look at the example.js -
var Section  = React.createClass({
    render: function () {
        return (<div>          
                    hi
                </div>);
    }
});
ReactDOM.render(<Section/>, document.getElementById("content"));

In the above code, i have created a simple section component, which says hi and then i make use of ReactDOM to render this section in the "content" div.

Please note - The case is very important here. If i make the name of the component as "section" instead of "Section" then it wont work.

That is all to begin with. Please explore more detail on React on its official site.

Saturday, May 28, 2016

Understanding npm and Grunt

npm
Javascript is not a language where your code gets compiled. So like .NET you can not just build the code and add dependencies and resolve it easily. In case of javascript, we need to add dependencies manually and need to make sure that the final HTML page do have reference to all these dependencies.
This is a very common step which everyone will have to do. So the idea came to automate all these steps and that is where the package manager and Grunt comes in.
If you have idea of .NET, there is nuget package manager. It helps us load the dependencies using nuget packages. Similarly in Javascript also, there are packages available to be reused. We can download these packages using node package manager(npm). In order to use the npm, we need to install it.
Detail about installation can be found on the official npm website.

package.json
In .NET packages we have package.config file which has all the detail about the package installed. In Javascript we have package.json available which help us configure the packages required.
Package.json has all the detail of your application, and its dependencies.
just execute "npm init" to create package.json file(we can create it manually as well).
Sample package.json –
{
    "name": "dummy-tutorial",
    "version": "1.0.0",
    "private": true,
    "license": "see LICENSE file",
    "description": "Dummy package.",   
    "dependencies": {
    },
    "devDependencies": {      
    } 
}
Dependencies – Mention the dependencies required in the project and will be required in actual production. Dependencies mentioned here become part of your bundle that you will be  deploying.
devDependencies – Mention those dependencies which are required only for local development.
“npm install” – command will create node_module folder having all the packages mentioned in the package.json

Grunt – Grunt is a task running tool. You can configure multiple tasks one after another to be executed. Say you want to process a js file written with ES6 code into ES5 and then want to concat multiple of these files in to 1, then you can configure these tasks to be executed one after another.
Grunt is also a package which you need to install.
There is a Grunt.js file which is used by Grunt to understand the required module, their dependencies and the task that need to be executed.
Grunt file has 3 important parts –
1-   Initconfig
2-   Loadnpmtasks
3-   Register task
Sample Grunt.js file - 
module.exports = function (grunt) {
    grunt.initConfig({
       // Tasks configuration go here
    });
                //load tasks
    grunt.loadNpmTasks(/*task name*/);
                //optionally create custom tasks
    grunt.registerTask("default", [ /*array of tasks*/]);   
};

Sunday, May 15, 2016

Typescript overview

Today we will discuss some fundamentals of typescript.

What is Typescript?
Type script is nothing but a better way of writing javascript. At this point i am assuming that you are aware of basic of javascript. If you, you must already came across the power of javascript. The only issue with Javascript is that it is hard to structure it well. There are bunch of libraries available like knochout, angular, jquery, react etc. which give different kind of features. but Typescript is not just another library, instead it is wrapper around javascript with some set of rules within, which helps programmer to write javascript code in a neat and better manner.

Why do we need it?
In order to understand the need of typescript, lets think what is not doable or difficult to do in javascript -
Contract/Interface, class, inheritance these concepts are very common in programming, but these are not directly supported by javascript. If you think building a heavy javascript app(which is very common with modern browsers), it is very important and necessary to have these features available.
Typescript is something which give us strong"Types" in javascript and help us get rid of duck typing(if required). Class, interface, encapsulation, modules, strong types are in built in TypeScript.

How to use Typescript?
Typescript is required a compiler. It comes with Visualstudio 2015 by default, but we can also download and install it as a separate plugin.
Typescript code is written in ".ts" file. Once compiled, we get equivalent ".js" file. we can write any javascript code in .ts file as well, because every javascript is a valid typescript.
on the actual page we include the generated .js file.

Defining variable in Typescript -
var str : string;
var num : number;
var obj : object;
var dontknow : any;
var func : (args:any)=> any // func of type function taking input of type any and returning type any.
var bl : boolean;
var strArr : string[];

Modules in Typescript -
using module in typescript we can create namespacing and we should always create a namespace before writing any code in javascript.
typescript code -
module a.b.c {
    var a: string;
}

translate into javascript -
var a;
(function (a_1) {
    var b;
    (function (b) {
        var c;
        (function (c) {
            var a;
        })(c = b.c || (b.c = {}));
    })(b = a_1.b || (a_1.b = {}));
})(a || (a = {}));

Class and interface  -
Typescript supports classes and interfaces.
- we can define method as well as variables in interface, which help us creating type/model in javascript. An interface can have just variable, and no method also.
- In order to import any interface/class from other namespace, we can use "import" keyword.
- use "implements" keyword to implement an interface.
- use "export" key word to expose the given interface outside module.
- use public method to expose the method, or we can make methods and variables as private as well.
- there is no javascript generated for interface ,as it is only for type safety during compile time.

Following is example of typescript -
myInterface defines 1 method and 1 variable in it.
Class myClass implement myInterface and hence expose this variable and method.
we can control accessibility by private, public specifiers.

module a.b.c {
    import contract = a.b.Contract;

    class myClass implements contract.myInterface{
        public myvar: number;

        public mymethod(input1: string): number {
            return this.myvar;
        }
    }
}

module a.b.Contract {
    export interface myInterface {
        myvar: number;
        mymethod(input1: string): number;
    }
}

Javascript code -
var a;
(function (a) {
    var b;
    (function (b) {
        var c;
        (function (c) {
            var myClass = (function () {
                function myClass() {
                }
                myClass.prototype.mymethod = function (input1) {
                    return this.myvar;
                };
                return myClass;
            })();
        })(c = b.c || (b.c = {}));
    })(b = a.b || (a.b = {}));
})(a || (a = {}));

Including other libraries - 
As we know there are bunch of libraries available in javascript, how do we plug those in our typescript code?
Well every lib (or most of them) do expose a "type definition" for typescript(.d.ts). WE need to include that in our project and refer to that type definition file in our code to take advantage of it. Using this type definition file, we can refer to all APIs exposed by the lib and can write our code in typescript.
Example - say abc is a library and exposing a type definition file -
/// <reference path="abc.d.ts" />
using reference we included it in our code and can refer all the APIs within.