Thursday, August 18, 2016

ReactJS - Getting Started -2

In my previous post we discussed on creating a todo app and we have creates a list of todo where we passed data. Now let’s enhance the same todo app and see if we can add “edit” button. So we are going to make the list of todo as read only and once user click on edit button, the list should be editable.
By this example we will cover on how we can make different communicate with each other.
Initialization of app will not have any changes as such –
var _todos = [{id: 1, text: "This is one comment"},{id: 2, text: "This is *another* comment"}];
ReactDOM.render(,document.getElementById('todo'));
As there are 2 modes, editable and non editable, we will maintain a state to begin with.
Also we need to have a click handler for our edit button. In React, the data flows unidirectional and it is recommended to implement on the same line. In our code, todolist and edit button are 2 components loaded at same level(there is no parent child relation) so if we want to make communication between these components. We need to pass a handler from parent to child button. Once button is pressed, it will notify parent about this, and then parent can communicate this to child components via state change.
Edit button –
var EditButton = React.createClass({
    render:function(){
        return();
    }});
We created a html button and we have a prop associated with it – “onClick”. If you see carefully we have passed the handler in props from parent.so on click of the button we will be executing the handler passed.
TodoApp –
In toDoApp component, we modified the render function and have introduced “EditButton”. Also we introduced 2 functions – getInitialState and handleEdit.
getInitialState is function which sets the initial state of the component. We are require to put the default value of state that we are planning to use (else component will throw error).
handleEdit – this is the function we introduced so that we can handle the click of edit button in the parent. In this function we just modify the state of the component. Once the component’s state is modified, react will call the render function of component with new state. If we see that any child component need not to refresh, then we will have to explicitly stop its rendering.
var TodoApp = React.createClass({
    getInitialState: function() {
        return {
            editview: false            //by default read only view
        };
    },
    handleEdit:function(){
        this.setState({
            editview: true    // on click of edit, change state to editable.
        });      
    },
    render: function () {
        return (
           
                           

               
               
           
        );
}});
If you see above, we passed another prop as “editable” to ToDoList, which will make use this prop to set todo as editable or not.
There is not much change in the ToDoList, we are just passing new prop to Todo component.
var TodoList = React.createClass({  
    render: function(){
        var todos  = this.props.todos;
        var editable = this.props.editable;
        var todoNodes = todos.map(function(todo){return ();}            
    );
    return (
{todoNodes}
);
    }
});
In Todo component, we are just consuming this new field from prop and making the input as disable/enable.
var Todo = React.createClass({
    render: function(){
        var todo = this.props.current;
        var edit = this.props.edit === true;              
        if(!edit){
            return();      
        }
        return();      
    }});

ReactJS - Getting Started -1

This post is continuation on my previous post -
If you have not see it, i ll suggest to go over it first, that will give you basic understanding on React.
In this post we want to learn component structure and how component fit within each other. We will also cover how these component communicate with each other.
Let’s try to create a sample ToDo app which can render a list of ToDos. 
To begin with we will create a ToDoApp and will create child component within it and will render the todo.
Here is the structure of todo app – 

We need to create 3 components here- 
TodoApp
TodoList
Todo
Here is raw structure of each of them  - 
var TodoApp = React.createClass({
    render: function () { 
        return (
                     
        );
}});
var TodoList = React.createClass({    
    render: function(){        
        //render all todos ()
    );
});
var Todo = React.createClass({
    render: function(){
        return(
som items
);        
    }
});
This is how we will render the todo app – 
ReactDOM.render(,document.getElementById('todo')); // assuming there is a div with id “todo”
Lets try to fill all these components further and see if we can have working app. 
If we want to render something in our Todo app, we need to pass some data. In React we make use of props to pass any data from parent to child.
var _todos = [  {id: 1, text: "This is one comment"},  {id: 2, text: "This is *another* comment"}]; //Sample data
ReactDOM.render(,document.getElementById('todo')); // sample data passed as prop to TodoApp component.
Consume the props – 
We need to consume this data in TodoApp, so let’s modify our default implementation  - 
var TodoApp = React.createClass({
    render: function () { 
        return (
                     
        );
}});
If you see closely we consumed the todos pass using this.props.todos and passing it to TodoList as another prop “todos”.
let modify TodoList to consume this prop  - 
var TodoList = React.createClass({    
    render: function(){
        var todos  = this.props.todos; // Get list of todo from prop
        var todoNodes = todos.map(function(todo){return ();}); // loop over all items and create node for each
        return (
{todoNodes}
); // return the nodes 
    }});
If you see carefully we are looping over the todo list and then creating the node for each todo. We are passing the actual todo object as “current” prop in the todo component. Let have a look at modified code of ToDo - 
var Todo = React.createClass({
    render: function(){
        var todo = this.props.current;
        return(
{todo.id}- {todo.text}
);        
    }});
In the above component we are just displaying the id and text. 

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.