PU$]-[KAR's

… Every drop has ability to survive .


Leave a comment

ReactJS application using Webpack and ES 6

Good Morning Friends !!!

Till now, we have seen the basic stuff about the webpack and ReactJs application. We have seen the basic webpack properties which are necessary to bundle a simple application and we have seen one simple example of ReactJS. For more details you can go through my earlier posts such as Webpack BasicsReact … Getting started !!! and React … With example!.

Now it’s time to create a sample application using webpack bundler, ReactJs along with ES 6. So I have chosen to create a example using bootstrap card layout with a responsive design.

The reason behind choosing ‘card template layout’ as an example is that for sure these ‘card templates’ are going to rule the word in the future in terms of web designing and why not… They are more expressive than the web pages. By consuming very small space on page they express a lot of points about the product. So definitely they will be the leader in upcoming web design market.

Setting up the environment

  • Install Node:

    To begin with the setting the environment we have to install latest version of node first to use ‘npm’ commands.

  • Application directory:

    Now create a directory where we want to build our application. Let’s name it ‘CardApplication’.

  • Package.json:

    Now go inside this directory. Here, we have to create package.json. So open node command prompt for this directory’s path and use the following command. npm init
    This will create the package.json for us. The purpose of package.json is when we ship our code to any other directory to run the code we have to just fire ‘npm install’ command which will take to install all the dependencies listed in package.json. So always make sure that what ever the dependencies you are going to install should have entry in package.json file.

  • Webpack installation:

    Use the following command to install the weback. npm install --save-dev webpack
    npm install webpack-dev-server -g
    Now as discussed earlier webpack needs webpack.config.js file. So create the file with the name ‘webpack.config.js’ on the same level where ‘package.json’ is residing in.
    Let’s copy the following code to webpack.conf.js
    var path = require('path');
    var webpack = require('webpack');
    module.exports = {
    entry: './main.js',
    output: { path: __dirname, filename: 'bundle.js' },
    Watch: true,
    module: {
    loaders: [
    { test: /\.css$/, loader: "style-loader!css-loader"                        },
    {
    test: /.jsx?$/,
    loader: 'babel-loader',
    exclude: /node_modules/,
    query: {
    presets: ['es2015', 'react']
    }
    }
    ]
    },
    };

  • React installation:

    The following commands will install React and React Dom npm install --save react
    npm install --save react-dom

  • Babel:

    The following commands will install Babel  dependencies.
    npm install --save-dev babel-loader@6.2.1
    npm install --save-dev babel-core@6.4.5
    npm install --save-dev babel-preset-es2015@6.3.13
    npm install --save-dev babel-preset-react@6.3.13

Now we are done with the setting up the environment and ready to code.

Application over view:

This application will tell us in brief about the mega structures made in past like Pyramid, Taj Mahal etc. So we are going to create a card for every structure. This card will have its on image at the background and on mouse hover it will show semi background overlay with icons for few sample menu. These menu items are clickable.

Application walk through:

So I have created the sample application git repository for card layer demo from where you can refer the code while developing the application or you can download its zip file or clone it.

In this application I have divided the folder structure for components mainly in two parts.

  • Card:

    This folder is containing the basic structure for card design. This is a reusable components which will accept the values for its title, description text and background image.

  • Menu:

    This folder is containing the component which is responsible for bringing pop up overlay on mouse hover with image menu option like print etc.

  • Card Demo.jsx:

    This page is demonstrating the cards usage to the end user.

If you have clone the application repository just use command ‘npm install’ at the folder level where the package.json is residing and run the application with command ‘webpack-dev-server –inline’. Thepage will demonstrate you the cards explaining mega structures!

That’s all my friends…

Happy coding !!!


Leave a comment

React … With example!

Hey!

Today, we will go through the one of the basic example of react. In this post we will see how to build a react component and  how they interact and communicate with each other.

In this example we are going to create two buttons and based on the click of the button, we are going to change the state of the label i.e. changing the text of the label.

Example

So to begin with this we example, first we have to create ‘react Components’ for button and label. For button we can create a reusable component which takes the name and click function as the parameter. So we can reuse this button by passing the name and click function as per our requirement and the button will invoked the exact function which we have passes to it. This implementation will explain how the properties (props) can be passed from parent to child.

As you can look into the code, we are accessing the function and name using ‘this.pros.onclick’ & ‘this.props.name’. The props represents the attribute which we have supplied to Button component. And if you observe carefully we have passed different function to each button. In similar way the ‘Label’ has been implemented.

Now we will come to the part about the changing the label text on click. In react the important thing to keep in mind is that every change in UI is get handled through the state change. So in short to change the text on the click, we have to change the state of the application. Basically state is the collection of properties which defines the current state of the application.

The function ‘getInitializeState‘ is the function provided by react to intialize the state once and later on we can change the states. This is what we have done exactly the same with label. We have initialize label with some default value and we are changing the state of the label on click of the button. Behind the scenes when we change the state the ‘Render’ function will get called automatically and the receptive DOM will get re render. This is the example of stateful component. Just keep in mind that this state change approach will force ‘render’ method only in case of ‘stateful’ component. This will not be the case if we used stateless component. In that case we have wrap the stateless component in side stateful component or ‘redux form’ or any other options. We will discuss about the this stateless component in later posts.

That’s  all my friends… 🙂

 


Leave a comment

React … Getting started !!!

Hi folks,

Like angular, again one of the technology is getting evolved and i.e. ReactJS. ReactJS is really a way different from the AngularJS in all the manner but it looks quite good and interesting to me. After all giant ‘Facebook’ is behind it. 😉

So today to begin with ‘React’ I would like to share the key concepts and fundamentals to understand React.

Introduction:

React is a javascript library for building user interfaces. As it’s a library that means it is way all different than AngularJS of course. AngularJS is a framework not a library. Looking towards the react through the perspective of MVC, we may called React as ‘V’. That means React will take a responsibility to create an HTML page i.e. ‘View’ in our application.
React has been developed by Facebook and now lot of big players are using it too like Instagram, PayPal and so on.

Advantages Specifications of React:

Server side Rendering:

One of the good things about the react (unlikely to the previous version of AngularJS) React is supports the server side rendering if controls. So in certain scenarios like loading a heavy page at the beginning, it will perform faster.

Use of JSX:

JSX makes it easy to read the code of your components. It is also really easy to see the layout an how components are plugged with each other.
Combining functionality (JavaScript) directly to markup to create a component which is independent and self contained will make our life easier to maintain the code.

Virtual DOM:

React works of on the mechanism of rendering virtual DOM to the actual ‘DOM’ i.e. actual HTML. That means whatever components we write in react get stored in virtual DOM and before rendering them to HTML DOM, existing HTML DOM gets compared against virtual DOM. This allows react to work faster. Because after comparison between the DOM, virtual DOM allows only changes to get rendered in to HTML (i.e. instead of reloading whole virtual DOM only changes in the DOM will get rendered on to the page.)

Few keywords from the React:

Following are the frequently used key words in React on which react is basically based upon.

Component:

We can say that React is component based architecture. Everything in react is treated as the component. So whatever DOM structure we are going to create will be treated as component only.

Class:

We are using ‘class’ based approach to create DOM. Basics of ES6 can help you in this.

Render:

This is the key method in React. This will be responsible to render a DOM and The markup we return from render() methods in React components is called JSX. The markups in JSX are similar to HTML but finally they get transpiled in to JavaScript functions.
But Yes, there is a bit difference such as we need to us className instead of class just because it ‘class’ is getting referred as object here.

ReactDOM:

This is the object who is going to render our ‘component’ using the ‘render’ method.

That’s All !!!

These are the ‘must required’ points at least one should know before starting with. In upcoming post we will go through the actual example using React.

🙂


Leave a comment

Webpack Basics

Hello,

While using ES6, React.js it’s always recommended to use module bundler like ‘webpack’ so today I would like to share the basics of webpack in simpler manner. There are many of blogs already published on the internet but the main reason to post this blog is to consolidate the things under one roof and also share my personal experience and opinion while using webpack.

Webpack … Does is really required ?

There was a time where it was considered that there is no such need of any tool who takes care of the client side code for moduling, merging, generating builds automatically etc. etc. Because the at that time the code written in JavaScript was not that much vast and evolved as compare to today’s projects.
Day by day javascript is getting evolved. Now the developers are using TypeScripts, ES6 going one step ahead of javascript. SO of course there will be need of transpilers like ‘Babel’ to convert the code in javascript. And the use of javascript itself has been increased tremendously. Modules are being developed by parallel programming is going on with javascript. So there is of course a need of a tool who will take care of merging these files into single one. That’s why the module bundlers like webpack came into picture.

Major activities that can be handled by webpack

As discussed above module bundlers are the tools who take care about the all client side code. So we will just go through the important roles which webpack can perform to mange the client side code.

  • Combine the developed code at one place: Just discussed above in the world of parallel programming webpack takes care of combining all the modules that are created in different files to single file
  • Resolving dependency: Wile combing the files to one file webpack takes care of resolving the inter module dependency. That means if ‘student’ module dependent on module called ‘person’ in that case webpack will take care of having all the code of module ‘person’ will be present before executing the code for module ‘student’. We don’t have to care about the dependency. Webpack will do the job for our self.
  • Reduce the file size: Reducing the size of file is very important when the code goes on the production. Removing of just white space also makes a lot of different in file size and hence it will improves the performance as well. So webpack takes care of such things like removing white space, minification etc. So this things helps us to enhance the performance of application.
  • Transpilation:webpack alos supports the transpilers like Babel or any other too.

Getting started with webpack

To install webpack we can use simply node packet manger with following command npm install webpack –g

Now, to understand the the configuration of webpack we will consider that we have been added ‘webpack.config’ file at root folder (in project structure) with following configuration.
module.exports = {
entry: "./app/component/main.js",
output:{
filename:"public/bundle.js"
},
Watch: true,
module:{
loaders:[{
test:/\.jsx?$/,
exclude:/(node_modules)/,
loader:'babel'
}
]
},
resolve: {
extensions : [‘’,’.js’,’.myExtension’]}}

To begin with module.exports, this is the object that’s actually returned as the result of a require call.

entry: Key ‘entry’ refers the file along with its path in which we have written a code. Even we can give multiple files using array notation as well.

filename: Inside output, filename denotes the single file in which all code (which we have written in different files) is going to be get combined and will be consumed by the browser to run the file.

These are the basic configuration which we need to run the application using webpack.

To run the application there is no need to install any different webserver. We can use the webserver provided by webpack itself.
The command Npm insall webpack-dev-server –g will install the webserver.

No we can run our application with command ‘$webpack-dev-server’.
But this will contain default bar in browser so to avoid this bar we can use command ‘$webpack-dev-server- -inline’

watch: To rerun the application every time whenever we make a small change in file is a tedious job. So if we set ‘watch’ to true, This will take care of rerun the application on every change.

Now we will look at the loader section. Till this point we were looking to run application with simple javascript files but as we are using react.js, ES6 we have to provide transpiler details in loader section so that files using ES6 etc. will get transpiled into javascript file.

test: This will takes care to run the test file as we are going to specify for this key. We can specify our own custom names or path to make repository of test files too.

exclude: As name suggested this will exclude the files, currently we have set this to exclude files from node_modules folder.

loader: Currently This we have set to ‘Babel’ transpiler.

resolve: This is a section which specify what are the file types that we can process without giving the specific extension. The list of extension can be given in array including any custom extension as well.
By default webpack will process files with ‘js’ extension.

We can add preorders such as jsHint for linting errors by adding key preloader in webpack.config file.

That’s all folks !!!


Leave a comment

ng-if OR ng-show … ?

Good morning!!!

We always hear about prefer ‘ng-if’ than ‘ng-show’ but why??? What is the reason behind it? Then where we need to use ng-show and not ng-if? So today, I will be explaining these things in brief.

How they work …

First we will understand how ‘ng-if’ and ‘ng-show’ works.
In case of ng-if, control will gets rendered on to the page only when ‘if’ condition gets satisfied. Otherwise it will not get rendered on to the page.
Where as in case of ng-show all controls will get rendered on the page but only those controls are visible who have satisfied the condition for ng-show.

ng-if

In normal scenarios where we want to load controls conditionally, it is better to use ng-if because the controls which are required only those will get rendered on the page. This will even make page a bit lighter as well and performance will get improved too.
Even ng-if makes developer’s life easier especially validating the controls (like textboxes) using form validations (e.g. required field validation). The reason is in this scenario text box which are visible on the page will get validated because rest of the controls are not even rendered on the page. But if we use ng-show the controls which are hidden will also fire the validation because though they are not visible, they are already loaded on the page. So ng-show will complicate the scenario for validation.

ng-show

Now where we can use ng-show??? Consider a scenario where you want to maintain the state of controls (tough they are hidden because when ever you choose the same option again you want those controls back in the same state as they were in previous).

In this scenario we can use ng-show because all controls are already rendered on the page (just they may not visible). So these all controls will maintain there state always where as ng-if if will not allow controls to get rendered so controls will not be able to maintain there states. So in such scenario one can go for using ng-show instead of ng-if.

That’s all my friends!


Leave a comment

DOT LESS … What & Why ?

Hello,

Today we will be discussing few simpler points about ‘LESS’ programming i.e. one of the preprocessor for writing ‘CSS’. So to begin with …

What is DOT LESS?

Less is the preprocessor of Css and every one is well familiar with Css. It means that ‘Less’ is a style sheet which is generated dynamically and it can be compiled into Css.

Why LESS?

Now one can fairly argue that why we would add an extra layer before Css because everything is going to be converted into Css only. Then why anyone would put an extra burden?
And the answer lies in the extra features that have provided by the Less to write Css in more simpler manner and in more organized way. So First we will see the features of Less on by on and the finally we will come why you would consider Less instead of writing Css directly.

  • Adds ‘Right’ things at ‘Right’ place: We know Css is a dumb language. In Css we go on adding stuff but no variables, no functions, no reusability at all. Less empowers the Css by adding such features like variables, mixins, and functions.
  • Time Saving: You’ll be amazed at how much time you save when you aren’t forced to write the same things over and over.
  • Easier to maintain: Being able to use variables, mixins, and functions means you can define a value or group of values. This makes developer’s life easy. By declaring all this stuff at the beginning of your document, instead of through it, making it easier to make changes later.
  • Makes Css in more organized structure: Less supports nested hierarchy of controls.

To be going forward we are going to see these features in details.

Features of LESS

Now, here we will walk through few very important and widely used features of Less which helped to make developer’s life happier 🙂

  • Variables:Its pretty simple and straight forward thing. We can declare variables like constants and that can be reused across the files. e.g.
     @nice-blue: #5B83AD;
    @light-blue: @nice-blue + #111;
    #header {
    color: @light-blue;
    }
  •  

  • Mixins:Mixins are kind of setting a behavior rule to the application. Bunch of properties are declared together and can be reused across the application to apply certain behavior to certain controls.
    E.g. While setting up the border to any div or panel we will definitely declare certain properties repetitively, so these properties are can be bound together to create a mixin.
     .bordered
    {
    border-top: dotted 1px black;
    border-bottom: solid 2px black;
    }
    #menu a
    {
    color: #111;
    .bordered;
    }
     
    Here, if you look at ‘menu a’ has consumed mixin ‘bordered’, so even other classes like panel, div can consume this same mixin to apply the border in same way.
    Even we can pass parameters/varibles to the mixins as well so that we can pass our own values inside the mixins.
  •  

  • Nested Rules:Less follows the hierarchy of the DOM elements to declare nested styles.
    If you go through the following structure of CSS you will understand the point.
     #header
    {
    color: black;
    }
    #header .navigation
    {
    font-size: 12px;
    }

     
    So this Css says that DOM ‘header’ also contains class ‘navigation’ inside it. It is a bit difficult and tedious to write in Css manner but Less can understand the structure and provides a simpler way to declare styles using DOM hierarchy shown as below.
     #header
    {
    color: black;
    .navigation
    {
    font-size: 12px;
    }
    }

     Now, if you could observe we have used hierarchy of inside less itself i.e. header -> navigation.
  •  

  • Use of operators: Any number, color or variable can be operated on. Here is an examples:
     
    @var: 5px + 2.
     
    Here we can observe that Less is smart enough to understand that ‘px’ is a unit so adding ‘2’ will result into ‘7px’. Finally ‘var’ will hold value as 7px.
  •  

  • Importing the files: Less provides the features of importing the variables and mixins from the different file. This helps developer to modularize the code in better manner. The import statement will follow the following syntax.
     
    @import “@{themes}/fileName.less”;
     
  •  

  • Functions: Less provides built-in Functions as well. Like percent, saturation (incase of color saturation) and many more. So developer need not to takecare of such small things and in fact these things are widely used in styling.

Apart form these Less also provides many more features like:

     
  • Lazy loading: In this case Variables are lazy loaded and do not have to be declared before being used.
  •  

  • Lazy loading: Less can perform looping. We ca write recursive mixins, iterations in less as well.

As we dig into Less more and more the list is getting bigger and bigger.

To summarize it…


My friends, at first glance using ‘Less’ will look like more tedious but form my personal experience I can say that just start using it & more you use will more you love it. 😉


Leave a comment

Jasmine unit test for ‘Directive’

Hey,

Today, we will go through unit tests for directive using ‘Jasmine’. We have to keep one thing in mind that Jasmine unit test is not ‘E2E’ testing framework. So we have to test our application module wise i.e. testing directives and services, controllers separately. To begin jasmine tests for directive we will consider a simple and very famous directive- ‘custom validation directive’.

Directive code:

var INTEGER_REGEXP = /^\-?\d*$/;
app.directive('integer', function() {
return {
require: 'ngModel',
link: function(scope, elm, attrs, ctrl) {
ctrl.$parsers.unshift(function(viewValue) {
if (INTEGER_REGEXP.test(viewValue)) {
ctrl.$setValidity('integer', true);
return viewValue;
} else {
ctrl.$setValidity('integer', false);
return undefined;
}});}};});

This directive is simply responsible to check weather input is of type integer or not.

To test this directive we have to use a bit different technique that the previous. First we have to create a html on the fly which consumes this directive and then we have to assign the input value to this html. Once the value gets assigned, this custom validation will get fired.

The following code will describe the unit testing for this directive.

Unit test:

describe('directives', function() {
var $scope, form;
beforeEach(module('testDirective'));
beforeEach(inject(function($compile, $rootScope) {
$scope = $rootScope;
var element = angular.element("< form name="form">< input ng-model="model.integerInput" name="integerInput" integer />' +'</form>");
$scope.model = { integerInput: null }
$compile(element)($scope);
form = $scope.form;
}));
describe('integer', function() {
it('should pass with integer', function() {
form.integerInput.$setViewValue('3');
$scope.$digest();
expect($scope.model.integerInput).toEqual('3');
expect(form.integerInput.$valid).toBe(true);
});
it('should not pass with string', function() {
form.integerInput.$setViewValue('a');
$scope.$digest();
expect($scope.model.integerInput).toBeUndefined();
expect(form.integerInput.$valid).toBe(false);
}); });});

Explaination:

As discussed earlier, here is one important thing to note that while creating unit test we have created a html on the fly which consumes our directive. So to convert this html string to ‘DOM’ we used $comiple().
Keep it in mind that we have warped ‘input’ control inside ‘form’ element because angularJS does not fire the validation until and unless form gets dirty so it is recommended that we should wrap it inside ‘form’.
‘$setViewValue’ is used to set the value to input control. Please don’t use DOM manipulation to set value to the input control. The reason behind this is by setting this value using ‘DOM’ handling ‘form’ will never come to know that something has been changed on the ‘form’ so eventually form will not be considered as ‘dirty’ and validation will not get fired and test will get failed. So proper way to use ‘$setViewValue’.
Finally trigger the digest cycle to let the test know the run-time changes.

And now test is set ready to ‘Go Green’…