Tuesday, October 16, 2018

Getting started with ReactJS Bootstrap Tutorials with examples | reactstrap tutorials

In this blog post, We will explore how to integrate bootstrap framework with ReactJS library.

react bootstrap reactstrap tutorial example

react bootstrap components

Bootstrap is a popular opensource HTML, Javascript and  CSS framework for building responsive applications targetted to Desktop and mobile. Bootstrap developed based on JQuery framework.In this tutorial, We are going to learn bootstrap integration in react library without JQuery.React is one of popular javascript framework for building client-side applications. Since Bootstrap is based on Jquery library, It is very difficult to integrate with React Library.
There are multiple npm projects that available as npm package which we can integrate into react easily.
The advantages with the npm package is we can use well tested ready-made components for grid and other bootstrap UI components.

We will pick reactstrap npm package since it is using bootstrap latest version and updating frequently.

Prerequisite

Node and npm commands installation 
First, make sure that install nodejs environment on your operating system. Once installed, Please issue the below commands to check node and npm command working or not
B:\Workspace\blog\reactapp\helloworldreact>node --version
v8.10.0

B:\Workspace\blog\reactapp\helloworldreact>npm --version
5.6.0
if the command is giving version number, that means it is installed correctly
Here are the following sections explains about

  • React bootstrap integration using reactstrap example
  • React Bootstrap button component example

React Application Generation using create-react-app

First Create reactJS application using create-react-app cli tool. This post will not give steps to create react application,. You can check my previous post on create-react-app cli example

Install npm bootstrap dependency in react application

reactstrap has a dependency on bootstrap npm library. Install both dependencies in your application using npm or yarn command line
npm install --save bootstrap reactstrap
yarn add bootstrap reactstrap
Once dependencies are installed, This adds bootstrap and reactstrap folders in node_modules folder of an application and also This adds an entry in the dependency section of package.json Here is my package.json file
{
  "name": "helloworldreact",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "bootstrap": "^4.1.3",
    "react": "^16.5.2",
    "react-dom": "^16.5.2",
    "react-scripts": "2.0.5",
    "reactstrap": "^6.5.0"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": [
    ">0.2%",
    "not dead",
    "not ie <= 11",
    "not op_mini all"
  ],
  "devDependencies": {
    "uuid": "^3.3.2"
  }
}
This installs required dependencies in the application

Import reactstrap components and bootstrap CSS file 

reactstrap provides each UI element in the form of component. Import bootstrap.css in app/index.js
import 'bootstrap/dist/css/bootstrap.css';
import button component in application - app/app.js
import { Button } from 'reactstrap';

Button Component example



import React, { Component } from 'react';
import './App.css';
import { Button } from 'reactstrap';
import 'bootstrap/dist/css/bootstrap.css';

class App extends Component {
  render() {
    return (
      <div className="App">
        <div>
        <Button color="primary">primary Button</Button>{' '}
        <Button color="secondary">secondary Button </Button>{' '}
        <Button color="success">success Button</Button>{' '}
        <Button color="info">info Button</Button>{' '}
        <Button color="warning">warning Button</Button>{' '}
        <Button color="danger">danger Buton</Button>{' '}
      </div>
      </div>
    );
  }
}

export default App;
react development server is started using npm start command and following is the screenshot of the button output

react bootstrap button example

Gitignore file Generator examples - Eclipse | Intellij |Netbeans

In this blog post, We are going to  learn how to git ignore files in IDE - Eclipse, IntelliJ, and Netbeans
In my previous post, We are going to learn gitignore file tutorials with examples

gitignore file

gitignore file contains patterns of files and folders which prevent from commiting to git repository when the code is committed and push to a remote repository
This file is specific to IDE and Operating systems and languages.
We are going to see following examples for different IDEs like Eclipse and IntelliJ. For any project created/imported in IDE, It creates metadata files which we can ignored for git commit process

Eclipse examples

Eclipse is a popular IDE used in java projects. Basically, Any java project contains following things Java source code which can not be ignored metadata data files which can be ignored Output of java project build using can be ignored Eclipse metadata files are .classpath and .project .project file created when the application is created /imported in eclipse. This contains project information .classpath file contains java source files considered The below example specifies the below things git ignore for file and folder for maven projects git ignore file and directories for eclipse projects
# Eclipse metadata files that can be ignored
.classpath
.editorconfig
.factorypath
.gitattributes
.project
.settings/
bin/

target/
# maven project related ignore files and directories
.mvn/
target/

IntelliJ examples 

gitignore file can be created in intellij manually. By default, intellij adds .idea files automatically This example talks about below things Npm angular project git ignore files in intellij maven java application git ignore files in the intellij editor
# Add any directories, files, or patterns you don't want to be tracked by version control
/.metadata/
.classpath
.editorconfig
.factorypath
.gitattributes
.idea/codeStyles/
.idea/inspectionProfiles/
.idea/modifysf.iml
.idea/modules.xml
.idea/typescript-compiler.xml
.idea/workspace.xml
.mvn/
.project
.settings/
README.md
mvnw.cmd
node/
node_modules/
package-lock.json
src/main/webapp/assets/sf/manifest.json
src/main/webapp/assets/sumfox-logo-167x33-Copy.png
target/
yarn.lock
/.idea/jsLibraryMappings.xml
/.idea/libraries/tsconfig_roots.xml
/.vscode/settings.json
/out/production/main/com/eclinso/sumfox/config/MethodSecurityConfiguration.txt
/src/main/main.iml
/.idea/misc.xml
/.idea/libraries
.idea
libraries

Netbeans examples 

Netbeans has specific build structure which we need to know before ignore the files. Here is sample file
**/nbproject/private/
build/
nbbuild/
target/
nbdist/
.nb-gradle/

.gitignore file tutorials with ignoring files,directories examples |git ignore file beginner guide

In this blog post, We are going to learn gitignore file tutorials with examples.

.gitignore file 

.gitignore is a file used by git tool to ignore the files and directories during committing source code changes to remote repository. Usually, ignore files or directors specific to local code bases or output of generated project running which are not required to commit to the remote repository. Each line in the file contains rules or patterns. Comment can be documented using # symbol.

.gitignore file example

This is an example for the gitignore file for node_module folder or directory of nodejs projects. In nodejs applications, the node_modules directory contains dependencies which are local to operating systems.
.gitignore file

# application dependencies
node_modules/ 

# application npm log file
npm-debug.log*

How to Create a gitignore file 

gitignore file can be created locally or globally
global repository generation 
 These files are global git ignore files or directories which applies to all git repositories in your host. This is a single file for each operating system You can create a .gitignore_global on your user root of your operating system using Text Editor. Once the file is created with list of git ignore files and directories, You need to tell the global gitignore file to git using below command
git config --global core.excludesfile ~/.gitignore_global
local repository generation 
.gitignore file is created in each git repository which is local to git repository. you can create a local gitignore file using a text editor with all git ignore files and folders. gitignore location is placed in the root of the repository

How to change git ignore file permission? 

Gitignore permissions issues will not be occured in windows, There are issues in Linux and Unix Operating Systems. core.fileMode will not track file permission changes For Local gitignore file permission changes
git config core.fileMode false 
For Global gitignore file permission changes
git config --add --global core.filemode false

templates 

 gitignore file is different for operating systems and language and frameworks. You can find here  list of all available templates

npm-check-updates npm package - update dependencies in package.json|bower.json

In this blog post, We are going to learn npm-check-updates npm package to update dependencies in package.json and bower.json.

npm-check-updates npm package 

npm check updates package is used to check all dependencies in package.json of a node js project and update dependencies to latest versions. This package works by updating following configuration files

  • package.json 
  • bower.json

This library solves all below problems of a NodeJS application
  • How to update all dependencies in package.json to latest versions?\
  • How to update devDependencies in package.json to latest versions?
  • Update dependencies in bower.json to the latest version

Setup npm-check-updates or ncu package globally

node and npm command should work before install npm-check-updates. Please install npm-check-updates globally using npm install command. Once this is installed, ncu command is available
npm i -g npm-check-updates
B:\Workspace\blog\angularapp>ncu --version
2.14.1

How to check outdated dependency in package.json 

To update any packages to latest versions, First, you need to check outdated old version, Please issue npm outdated command The below example checks outdated dependencies in angular package.json
B:\Workspace\blog\angularapp>npm outdated
Package                        Current  Wanted   Latest  Location
@angular-devkit/build-angular    0.7.5   0.7.5    0.8.5  angularapp
@angular/cli                     6.1.5   6.1.5    6.2.5  angularapp
@types/node                      8.9.5   8.9.5  10.12.0  angularapp
codelyzer                        4.2.1   4.2.1    4.5.0  angularapp
jasmine-core                    2.99.1  2.99.1    3.2.1  angularapp
karma                            1.7.1   1.7.1    3.0.0  angularapp
karma-jasmine-html-reporter      0.2.2   0.2.2    1.3.1  angularapp
protractor                       5.3.2   5.3.2    5.4.1  angularapp
ts-node                          5.0.1   5.0.1    7.0.1  angularapp
tslint                           5.9.1   5.9.1   5.11.0  angularapp
typescript                       2.7.2   2.7.2    3.1.3  angularapp

How to check dependencies and update to latest versions?

First list out all the package with current versions and latest versions of package.json
B:\Workspace\blog\angularapp>ncu
Using B:\Workspace\blog\angularapp\package.json
[..................] \ :
 @angular-devkit/build-angular   ~0.7.0  →    ~0.8.5
 @angular/cli                    ~6.1.1  →    ~6.2.5
 @types/node                     ~8.9.4  →  ~10.12.0
 codelyzer                       ~4.2.1  →    ~4.5.0
 jasmine-core                   ~2.99.1  →    ~3.2.1
 karma                           ~1.7.1  →    ~3.0.0
 karma-jasmine-html-reporter     ^0.2.2  →    ^1.3.1
 protractor                      ~5.3.0  →    ~5.4.1
 ts-node                         ~5.0.1  →    ~7.0.1
 tslint                          ~5.9.1  →   ~5.11.0
 typescript                      ~2.7.2  →    ~3.1.3

Run ncu with -u to upgrade package.json
This will only just displays the result to console and not updated package.json Next update each dependency in package.json to latest versions
B:\Workspace\blog\angularapp>ncu -u
Using B:\Workspace\blog\angularapp\package.json
[..................] \ :
 @angular-devkit/build-angular   ~0.7.0  →    ~0.8.5
 @angular/cli                    ~6.1.1  →    ~6.2.5
 @types/node                     ~8.9.4  →  ~10.12.0
 codelyzer                       ~4.2.1  →    ~4.5.0
 jasmine-core                   ~2.99.1  →    ~3.2.1
 karma                           ~1.7.1  →    ~3.0.0
 karma-jasmine-html-reporter     ^0.2.2  →    ^1.3.1
 protractor                      ~5.3.0  →    ~5.4.1
 ts-node                         ~5.0.1  →    ~7.0.1
 tslint                          ~5.9.1  →   ~5.11.0
 typescript                      ~2.7.2  →    ~3.1.3

Upgraded B:\Workspace\blog\angularapp\package.json
This will updates dependencies versions to latest versions in package.json. Here is updated package.json files
{
  "name": "angularapp",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^6.1.0",
    "@angular/common": "^6.1.0",
    "@angular/compiler": "^6.1.0",
    "@angular/core": "^6.1.0",
    "@angular/forms": "^6.1.0",
    "@angular/http": "^6.1.0",
    "@angular/platform-browser": "^6.1.0",
    "@angular/platform-browser-dynamic": "^6.1.0",
    "@angular/router": "^6.1.0",
    "angular2-uuid": "^1.1.1",
    "core-js": "^2.5.4",
    "rxjs": "^6.0.0",
    "zone.js": "~0.8.26"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~0.8.5",
    "@angular/cli": "~6.2.5",
    "@angular/compiler-cli": "^6.1.0",
    "@angular/language-service": "^6.1.0",
    "@types/jasmine": "~2.8.6",
    "@types/jasminewd2": "~2.0.3",
    "@types/node": "~10.12.0",
    "codelyzer": "~4.5.0",
    "jasmine-core": "~3.2.1",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~3.0.0",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "~2.0.0",
    "karma-jasmine": "~1.1.1",
    "karma-jasmine-html-reporter": "^1.3.1",
    "protractor": "~5.4.1",
    "ts-node": "~7.0.1",
    "tslint": "~5.11.0",
    "typescript": "~3.1.3"
  }
}

How to update dependencies to latest versions in bower.json 

Like a package.json package update, We can use ncu command with option -m
ncu -m bower.json

Monday, October 15, 2018

Beginner guide to Package.json file tutorial with examples in Nodejs Applications

In this blog post, We are going to learn package.json tutorials with examples

Package.json file 

package.json is a JSON configuration file of a nodejs and javascript based projects. which contains key and value of elements of a  Nodejs based applications. This always contains in application root folder. This will be used by npm command for build/start/testing your javascript based applications. This will help other developers to track the application dependencies and versions
This file can be created in many ways as follows
  • Angular/ReactJS/VueJS CLI automatically
  • npm init command
  • Manually create file 
package JSON file contains the following properties
  • Project metadata like name, version etc
  • Dependencies of application - dependencies,devDependencies etc
  • npm command line automated Scripts 
  • repositories,browserlist, and engine support
 package.json file is used in below Nodejs Based application types
  •  Front-end based apps using Angular, ReactJS and Vuejs etc..
  •  Backend applications using MEAN or MERN Stack

package.json file example creation 

This example can explain different ways to create a file

  • package.json file creation with CLI prompt using npm init 
  • default package.json creation with default values using npm init -yes command


B:\Workspace\blog\reactapp>npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.

See `npm help json` for definitive documentation on these fields
and exactly what they do.

Use `npm install ` afterwards to install a package and
save it as a dependency in the package.json file.

Press ^C at any time to quit.
package name: (reactapp) nodeapp
version: (1.0.0)
description: This is node based application
entry point: (index.js)
test command:
git repository:
keywords:
author:
license: (ISC)
About to write to B:\Workspace\blog\reactapp\package.json:

{
  "name": "nodeapp",
  "version": "1.0.0",
  "description": "This is node based application",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}


Is this ok? (yes) yes

Example Minimal file 

This is a file created in the application root folder with a minimum configuration of an application
{
  "name": "nodeapp",
  "version": "1.0.0",
  "description": "This is node based application",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}
We have created a minimal package.json file
Name is the name of the application
version is the current version of the application
Description is a long text description about projects
main - this contains entry point script code of the application
Author is Name of the developer
License- license information of an application. This will be useful when you are publishing your project as npm package so that other developers can use this project based on it
scripts - This contains automated scripts which you can run using the name of the script specified. This actually contains npm commands to run via command line
repository - This is pointed the scm code location of the application
engines - This contains an array of entries which contains nodejs/npm version works for this application

"engines": {
  "node": ">= 8.0.0",
  "npm": ">= 3.1.0",
}
Browser list This will specify the list of supported browsers for your application

npm install - add a dependency in package.json 

Once the basic package.json file is created, you can install node package using npm install --save package name command. The below example explains about following things How to install npm modules/packages in nodejs applications How to add dependency and devdependencies to nodejs project The below command installs sweetalert and lodash module to nodejs project.
npm install --save sweetalert
npm install --save-dev lodash
The above commands create one entry in the dependencies section and other entry in devDependencies section of package.json. Here is updated package.json file

  "dependencies": {
    "sweetalert2": "^7.26.9"
 },
 "devDependencies": {
    "lodash": "^4.17.10"
 }

npm uninstall - remove the dependency in package.json 

You can uninstall dependencies from the application using npm uninstall command The below example explains about following things How to uninstall npm modules/packages in nodejs applications How to remove dependency and devDependencies from nodejs project The below command uninstalls sweetalert and lodash module to nodejs project.


npm uninstall --save sweetalert
npm uninstall --save-dev lodash
The above commands remove an entry from dependencies and devDependencies section of package.json

  "dependencies": {
 },
 "devDependencies": {
 }

How to update dependencies to latest versions automatically in a nodejs project.

package.json contains all dependencies. It is very painful to update each package to the latest version. There are many ways we can do that, npm-check-updates is the command line utility tool used to update all dependencies to latest version and will update the latest versions in package.json. Install npm-check-updates globally using npm install Once installed, ncu command will be available update all packages to the latest version using ncu -u command Finally install all packages in an application using npm install command
npm i -g npm-check-updates
ncu -u
npm install

Dependencies Types

There are a lot of dependencies types in package.json

  • Dependencies for production build 
  • devDependencies for a development build 
  • peerDependencies for production build minus transitive dependency optionalDependencies - optional or conditional dependencies

npm package versions

package.json dependencies contain package and version. The version can be configured or updated with below different options
Versions can be prefixed with a caret(^)  and tilde(~) and other symbols as below
For example 
^2.1.0 - This package can be updated to minor versions like 2.1.1 or 2.2.0
~2.1.0 - This package can be updated to minor versions like 2.1.1 but not 2.2.0
* means any version can be updated
>2.1.0 Any version which is greater than 2.1.0 can be updated
>=2.1.0 Any version which is greater than or equal 2.1.0 can be updated <2.1.0 Any version which is lesser than 2.1.0 can be updated
<=2.1.0 Any version which is lesser than equal 2.1.0 can be updated

What is the difference between Dependencies, DevDependencies, and peerDependencies in package.json

Dependencies are actual dependencies used to run your application. This will be used for Production. This will also install transitive dependencies, Transitive dependencies are if package 1 dependent on package 2 which dependent on package3

if package 1 is installed, package2 and package 3 also installed automatically.

This will be installed using npm install --save command. This always contains like Angular/Vue/react l, libraries as dependencies

DevDependencies 
these dependencies are development dependencies of an application.  This are needed as a dependency during development like testing frameworks -mocha or karma. 
This will not be published as part of production build. This will not install transitive dependency
This will be installed using npm install --save-dev command. This always contains like testing frameworks or documentation libraries

peerDependencies

These are dependencies like production but transitive dependencies are not installed. 
This will be installed using npm install --save command.

what is private key in package.json

package.json contains private key and value are true/false
if private is true, the application cannot be published as npm package. This is used to avoid publishing it to repository accidently

Beginner Guide to manifest.json file example tutorial | Web App Manifest example with tutorials

In this blog post, We are going to  learn web app manifest - manifest.json file example with tutorials.

web app manifest - manifest.json file 

web app manifest is a JSON file that contains metadata information of a web application. It specifies to the browser how it looks User interface during application installed on mobile or desktop.manifest.json is also called manifest.webmanifest. This can also be used in progressive web applications that look web applications as native apps. In browsers like chrome, the manifest file is required to enable add to home screen prompt feature
Manifest.json file can be used by different types of following applications
  • Web Applications or Desktop
  • Mobile Applications
  • Progressive Web Applications PWA
  • Chrome Extension Applications
manifest json file Supports following browsers and devices
  • Firefox 
  • Chrome
  • Safari
  • Android apps
  • IOS apps

manifest.json Sample file example

Here is sample manifest.json sample file which contains basic required properties like name,icons and start_url. remaining properties are optional.


{
  "name": "Todo PWA Application",
  "short_name": "Todo",
  "description": "To Do Progressive web application.",
  "start_url": "./index.html?home=true",
  "icons": [
    {
      "src": "/icons/todo-36.png",
      "sizes": "36x36",
      "type": "image/png"
    },
    {
      "src": "/icons/todo-48.png",
      "sizes": "48x48",
      "type": "image/png"
    },
    {
      "src": "/icons/todo-512.png",
      "sizes": "512x512",
      "type": "image/png"
    }
  ],
  "theme_color": "#111111",
  "background_color": "#DDDDDDD",
  "display": "fullscreen",
  "orientation": "portrait"
}

Properties 

name:- Application name that displays the value on user home screen
short_name:- shorter name of the application. This will be displayed during installation of add to home screen feature
icons - These are icons to be used in application installation, add to home screen, splash screen: This will contain a collection of images that will be displayed when a user adds the website to home screen
start_url This will be default URL when application is started. The landing page of application startup
theme_color- this is the color of the application toolbar background_color this specifies the color of the splash screen
Display - this specifies the application display when it is started, the values are fullscreen, standalone,minimal-ui,browser Orientation - orientation mode of application - landscape or portrait

How to include manifest json file in web application

We can include the manifest.json file in the head using link tag of HTML web page. This tells to the browser about manifest.json.
<link rel="manifest" href="manifest.json">
manifest json file has provided following features in applications
  • Application metadata information like name,icons and start_url etc.. 
  • Add to home screen feature 
  • Spalsh screen details 
  • Application installation prompt information Privacy and content guidelines Permissions details
  • Installation and uninstallation events 
  • Application Display and orientation Configuration details

Sunday, October 14, 2018

Getting started with create-react-app Cli tutorials | reactjs Cli tutorials

In this blog post, we are going to learn the creation of React Application using React CLI tool.

React CLI tool introduction

React Framework is an opensource component framework from Facebook for developing User interface applications. It is a popular library. For creating react application manually, It is very difficult to create react application. Manually need to add configuration required for creating react application. React Team provides create-react-app cli tool to create a React Application from scratch without writing manually.
The following are prerequisite for creating react application

Node and NPM command installation

First Nodejs Installation on your operating system. NodeJs provides node and npm command line tools. Please issue the below command to check nodejs and npm installation
B:\Workspace\blog>node --version
v8.10.0
B:\Workspace\blog>npm --version
5.6.0

if this gives correct version numbers, then we can assume that NodeJS installed correctly.

create-react-app cli npm package installation

Once node and npm is installed, Please install create-react-app npm package
npm install -g create-react-app
This will installs create-react-app npm package globally and create-react-app command works on any folder The below command checks create-react-app installation
B:\Workspace\blog\reactapp>create-react-app --help
Usage: create-react-app  [options]

Options:

  -V, --version                            output the version number
  --verbose                                print additional logs
  --info                                   print environment debug info
  --scripts-version   use a non-standard version of react-scripts
  --use-npm
  --use-pnp
  -h, --help                               output usage information
    Only  is required.

    A custom --scripts-version can be one of:
      - a specific npm version: 0.8.2
      - a specific npm tag: @next
      - a custom fork published on npm: my-react-scripts
      - a local path relative to the current working directory: file:../my-react-scripts
      - a .tgz archive: https://mysite.com/my-react-scripts-0.8.2.tgz
      - a .tar.gz archive: https://mysite.com/my-react-scripts-0.8.2.tar.gz
    It is not needed unless you specifically want to use a fork.

    If you have any problems, do not hesitate to file an issue:
      https://github.com/facebook/create-react-app/issues/new
Once cli is installed, Create a React Application

Create React Hello world application using cli tool 

This is an example for react app creation using cli with an example
First, go to the directory where we need to create react application. This will install React boilerplate application with initial configuration
B:\Workspace\blog\reactapp>create-react-app helloworldreact

Creating a new React app in B:\Workspace\blog\reactapp\helloworldreact.

Installing packages. This might take a couple of minutes.
Installing react, react-dom, and react-scripts...

yarn add v1.5.1
[1/4] Resolving packages...
[2/4] Fetching packages...
info There appears to be trouble with your network connection. Retrying...
info fsevents@1.2.4: The platform "win32" is incompatible with this module.
info "fsevents@1.2.4" is an optional dependency and failed compatibility check. Excluding it from installation.
[3/4] Linking dependencies...
[4/4] Building fresh packages...
success Saved lockfile.
warning Your current version of Yarn is out of date. The latest version is "1.10.1", while you're on "1.5.1".
info To upgrade, run the following command:
$ curl -o- -L https://yarnpkg.com/install.sh | bash
success Saved 10 new dependencies.
info Direct dependencies
├─ react-dom@16.5.2
├─ react-scripts@2.0.5
└─ react@16.5.2
info All dependencies
├─ babel-plugin-dynamic-import-node@2.2.0
├─ babel-preset-react-app@5.0.4
├─ confusing-browser-globals@1.0.4
├─ eslint-config-react-app@3.0.4
├─ object.assign@4.1.0
├─ react-dev-utils@6.0.5
├─ react-dom@16.5.2
├─ react-error-overlay@5.0.5
├─ react-scripts@2.0.5
└─ react@16.5.2
Done in 353.50s.

Success! Created helloworldreact at B:\Workspace\blog\reactapp\helloworldreact
Inside that directory, you can run several commands:

  yarn start
    Starts the development server.

  yarn build
    Bundles the app into static files for production.

  yarn test
    Starts the test runner.

  yarn eject
    Removes this tool and copies build dependencies, configuration files
    and scripts into the app directory. If you do this, you can’t go back!

We suggest that you begin by typing:

  cd helloworldreact
  yarn start

Happy hacking!

create-react-app folder structure explanation

Here is folder structure of react application

react app folder structure

package.json file
This file contains all the meta information and dependencies of react application. Some of the configuration entries are as below
React application name using "name": "helloworldreact"
application current version using "version": "0.1.0"
private configuration to publish to npm registry using "private": true
Application dependencies using
"dependencies": {
    "react": "^16.5.2",
    "react-dom": "^16.5.2",
    "react-scripts": "2.0.5"
  }
Application scripts to start/build/test the application
"scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  }
node_modules folder 
This contains direct and indirect dependencies of a react application defined in package.json
public folder 
This folder contains static assets of a react application. This contains following files
index.html - This is starting and entry of an application
favicon.ioc - react application favorite header icon
manifest.json - This is the configuration for a progressive web application. This contains shortcut icons for android and IOS when added using add as home screen feature.
src folder
This is actual javascript source code of react web app. This contains js and css and svg

react app development server start

Application folder is created and now it is time to start the development server. Please issue the below npm command to start the server
B:\Workspace\blog\reactapp\helloworldreact>npm start

> helloworldreact@0.1.0 start B:\Workspace\blog\reactapp\helloworldreact
> react-scripts start

Compiled successfully!

You can now view helloworldreact in the browser.

  Local:            http://localhost:3000/
  On Your Network:  http://192.168.12.54:3000/

Note that the development build is not optimized.
To create a production build, use yarn build.
and output is
create-react-app cli example

Kiran

Saturday, October 13, 2018

Angular Button Click Event examples - Binding Event in Angular 4|5|6|7

In this blog post, We are going to learn how button click works, get value from input on button click

Angular Event binding - Button Click 

Usually, In any angular applications, User clicks on the button for form submission or navigation from one page to other using clicking button. Internally when the button is clicked, You need to handle some logic for form submission or navigate to some other page.
When the button is clicked, DOM EVEnt Click event is triggered, You have to handle code to handle this DOM event.
Button display logic is placed in HTML template page ie view. The trigger event is placed in the typescript component class. So user event information will be passed from view to component class. This is called Angular Event binding

Examples

We will see below examples
  • Angular Button Click event example
  • Get input value on button click event

Angular Button Click Event Example

Added below changes in app.component.html ie component template HTML file Created an HTML input button Added click event to a button, Here used bracket() symbol. the name placed inside is bracket is an event This will be called when the button is clicked by user Next is displayed the status using angular two-way binding which passes the data from/to view to the component. Data displayed using either ngModel or interpolation - {{}} approaches. Here data displayed using interpolation
<div style="text-align:center">
    <h1>
       Angular Button Click Event Example
    </h1>
    <button  (click)="clickEvent()" >
    Click Me</button>
    <h2>{{msg}}</h2>
 </div>
 
Event handling in Component In component class, You have to define the method for handling click event. This method si always called when user is clicked button In the component class defined msg variable of type string, On clicking button event, msg variable is updated with status "button is clicked" app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  msg:string;
  constructor() { 

   }

   clickEvent(){
    this.msg='Button is Clicked';
    return this.msg;
  }
}
 
Output is
Angular Button Click Event example

get Input text value on button click event example 

This example explains about display input value on button click button click input binding examples In HTML component, Input is defined with ngModel attribute which binds the value from view to component or component to view Displayed the value typed in the text box using interpolation

<div style="text-align:center">
    <h1>
       Angular Button Click Event Example
    </h1>
    <button  (click)="clickEvent()" >
    Click Me</button>
    <input type="text"  [(ngModel)]="msg">
    <h2>{{msg}}</h2>

 </div>
 
Typescript Component class on click event typed value to update to a new variable which displayed in HTML using interpolation

 import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  msg:string;
  msg1:string;

  constructor() { 

   }

   clickEvent(){
    this.msg1=this.msg
  }
}
 

Thursday, October 11, 2018

Angular UUID - Generate Unique Identifier with examples Angular4|5|6

In this blog post, We are going to learn how to generate Unique ID - GUID, UUID in Angular with examples.
Please see my previous posts on GUID with examples

Angular Typescript UUID

Unique Identifier generation is requirement in any programming language. It contains 128 bits in size separated by hypen with 5 groups.
Angular is mvc framework based on Typescript.GUID and UUID generates 128 bits of samthe e implementation.
This blog post works on all angular versions
  • Angular 2
  • Angular 4
  • Angular 5
  • Angular 6
There are a number of ways we can generate GUID
We have already npm packages available 

Example Usage

The example talks about following things
  • Generate GUID in typescript
  • Generator UUID in angular component

angular2-uuid npm package

First install angular2-uuid npm package using npm install command
npm install angular2-uuid --save
This installs and create a angular2-uuid dependency in node_modules and added one entry in dependency of package.json
Import UUID module in angular component
app.component.ts
import { Component } from '@angular/core';
import { UUID } from 'angular2-uuid';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  uuidValue:string;
  constructor() { 

   }

  generateUUID(){
    this.uuidValue=UUID.UUID();
    return this.uuidValue;
  }
}
HTML Template generation
Created button, onclicking the button, it calls function in angular component. UUID.UUID() generates unique identifier app.component.html
<div style="text-align:center">
    <h1>
       Angular Typescript UUID generation
    </h1>
    <button  (click)="generateUUID()" >
    Generate UUID</button>
    <h2>{{uuidValue}}</h2>
 </div>
Output is
Angular typescript UUID example

Vuejs - Generate Unique Identifier - UUID or GUID with example

In this blog post, We are going to learn how to generate UUID or GUID in the vuejs application with examples.
In my previous post, We already learned about a guide to GUID, UUID, DUID in javascript.

Vuejs Unique Identifier introduction

Unique Identifier Generation is required in any application of every language. This can be used in Database primary keys or you can store session id in front-end MVC applications like Angular or vueJS.
UUID or GUID is alias both refers same and contains 16 bytes or 128 bits in size separated in 5 groups by hyphens.

There are different ways to create a UUID in vuejs applications
  • Using existing npm packages like vue-uuid
  • Custom UUID code to generate a unique id

Example for Generating Unique Identifier using npm package

vue-uuid usage example

vue-uuid  is an npm package for Vuejs Applications. First, you need to install it using npm install command
npm install --save vue-uuid
This generates dependency in node_modules and adds an entry in the dependency section of package.json
Import UUID module in the application 
UUID is global module defined in vue-uuid. Before using this global object and properties, You need to import in your mail.js file. This vue-uuid is globally available by calling Vue.use with uuid main.js
import Vue from 'vue'
import App from './App.vue'
import UUID from 'vue-uuid'

Vue.use(UUID);

Vue.config.productionTip = false

new Vue({
  render: h => h(App)
}).$mount('#app')
Once globally configured, uuid object is available inside the template of your vue components.
Vue Component for UUID generation 
In the script tag of vue component, First import uuid object and calling uuid.v1() returns GUID or UUID
<template>
  <div id="app">
    <h1 class="uuid">{{ uuid }}</h1>
  </div>
</template>

<script>
  import { uuid } from 'vue-uuid' // Import uuid
  export default {
   data () {
      return {
        uuid: uuid.v1(),
    
      }
    }
  }
</script>

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>
Output is
1f5cdb80-cd7f-11e8-bf21-1dd90afe8dad

Custom UUID code to generate a unique id

You can copy the javascript function UUID generation code and create a method in vue component. display it in template

Guide to Unique identifiers - UUID, GUID, UDID - Javascript | Typescript

In this blog post, We are going to learn how to generate Unique Identifiers - UUID, GUID, UDID  in javascript/typescript/nodejs.
UUID, GUID, UDID  examples with javascript typescript

Unique Identifier Generator

In every programming language, We have a unique identifier to identify the resources or value or references. There are various names that identify the unique references. Generally Following are the frequently used in javascript applications.
  • Universally Unique Identifier - UUID
  • Globally Unique Identifier - GUID
  • Unique Device Identifier - UDID

Universally Unique Identifier - UUID

UUID is a universal unique identifier. It contains 16 bytes value that can be used to identify unique value.The value represents hexadecimal values. This can be used as a primary key in the database tables to uniquely identify the rows
16 bytes values are uniquely defined by RFC 4122

Globally Unique Identifier - GUID

GUID is Microsoft version of UUID. You can user alternatively both and functionality and usage are same.

Unique Device Identifier - UDID

This is mostly used in mobiles to uniquely identify the devices. It contains  40 hexadecimal characters in size. It can be mostly used in IOS devices to identify the device

Difference between GUID and UUID

Both uniquely identify the value. UUID scope is universal, GUID scope is global. GUID is Microsoft implementation of UUID. Both generate a 16 bytes characters separated in 5 groups hyphen 

Here is sample Unique identifier
38bcc565-59f8-4506-818c-9d9dd7cb7b11

GUID UUID uses

  • Primary keys in Database tables to uniquely identify rows
  • values to identify windows registries to identify windows resources
  • To identify the data spread across servers in big data 
  • Used in REST API for doing CRUD operations using the identifier

javascript - How to create a UUID or GUID with an example

There are various ways to create a GUID or UUID. This example creates UUID, GUID in javascript
function uuid() {
  var uuidValue = "", k, randomValue;
  for (k = 0; k < 32;k++) {
    randomValue = Math.random() * 16 | 0;

    if (k == 8 || k == 12 || k == 16 || k == 20) {
      uuidValue += "-"
    }
    uuidValue += (k == 12 ? 4 : (k == 16 ? (randomValue & 3 | 8) : randomValue)).toString(16);
  }
  return uuidValue;
}
console.log(uuid())
output is
c50a2fbe-99b9-4d90-b332-a1a054c946b4

Generate Unique Identifier in Nodejs with an example

npm package uuid is available to generate Unique identifier First install using below command

npm install uuid
Here is an example usage

const uuid = require('uuid/v1');
uuidv1(); 
Output is
6a72d3cd-2d53-4e0e-8acb-0e1c98331fe1

Typescript - generate UUID or GUID with an example 

In typescript applications, You can use npm package UUID. first install uuid package using npm install uuid command. In typescript file, import uuid package and directly use uuid() function as below
import { v1 as uuid } from 'uuid';
const id: string = uuid();

Tuesday, October 9, 2018

Vuejs Sweetalert.js - Beautiful popup or alert notifications with examples

In this blog post, We are going to learn How to create a popup in a vuejs application using the sweetalert framework

I already blogged about Sweetalert tutorials with examples and Alert Notifications with Angular here as follows

VueJS Alert Component

Alert is  a simple popup dialog box to give useful information to the user
Vuejs is a popular progressive javascript framework for creating single page applications.
Sweetalert is a vanilla opensource lightweight javascript to create a popup notification in javascript applications. The applications can be Jquery, Plain Javascript or NPM based applications like ANgular, Vuejs, and Reactjs

With sweetheart, We can achieve the following alert notifications
  • Alert notifications to give success, warning, error and informational message
  • Popup to Prompt the user to take input information
  • Confirmation alert
  • Responsive 
There are a lot of Vuejs plugin wrappers for providing sweetalert 
In this blog post, We are going to integrate vue-sweetalert2 in vuejs based applications.
This blog post covers two parts
  1. Vuejs Application Creation using vue cli tool
  2. Integrate Sweetalert in Vuejs Application with examples

Vuejs Hello World Application generation

Vue framework provides vue-cli tool to create vue application from scratch using vue create command. 
B:\>vue create vuesweetalertdemo

Vue CLI v3.0.0-rc.8
? Please pick a preset: default (babel, eslint)

Vue CLI v3.0.0-rc.8
✨  Creating project in B:\Workspace\blog\vuesweetalertdemo.
⚙  Installing CLI plugins. This might take a while...

> yorkie@2.0.0 install B:\Workspace\blog\vuesweetalertdemo\node_modules\yorkie
> node bin/install.js

setting up Git hooks
can't find .git directory, skipping Git hooks installation
added 1281 packages in 278.557s
�  Invoking generators...
�  Installing additional dependencies...

added 3 packages in 18.413s
⚓  Running completion hooks...

�  Generating README.md...

�  Successfully created project vuesweetalertdemo.
�  Get started with the following commands:

 $ cd vuesweetalertdemo
 $ npm run serve
This will have vuesweetalertdemo application created with predefined vue folder structure with the initial configuration. Go to the application folder, run npm run serve command to start vue js application.

Install and save Dependencies to application

To integrate SweetalertJS in VueApplicaiton, Go to the application root folder, vue-sweetalert2 package can be installed using npm or yarn or bower.


npm install -save vue-sweetalert2
or 
bower install vue-sweetalert2
or 
yarn add vue-sweetalert2
This command will do the following things
  • Install vue-sweetalert2 in your application and creates folder node_modules\vue-sweetalert2 in application root folder 
  • Added below entry in package.json
  "dependencies": {
 -----
    "vue-sweetalert2": "^1.5.5"
  },

Import VueSweetalert2 module in vue application.

To make use of third-party npm package functionality, FIrst, you need to import VueSweetalert2 module in main.js. Once imported, Application is able to access sweetalert objects and its methods.
main.js
import Vue from 'vue'
import App from './App.vue'
import VueSweetalert2 from 'vue-sweetalert2';
Vue.use(VueSweetalert2);

Vue.config.productionTip = false

new Vue({
  render: h => h(App)
}).$mount('#app')

Popup Simple alert Example 

This examples application has one button, on clicking the button, It shows an alert box with a simple ok button. App.vue
<template>
  <div id="app">
   <div> <img alt="Vue logo" src="./assets/logo.png"></div>
    <button v-on:click="displaySimplePopup">Click Me</button>
  </div>
</template>

<script>
  export default {
    data() {
        return {
          msg:''
        };
    },
    methods: {
        displaySimplePopup(){
            // Use Sweetalert
            this.$swal('Welcome to Vuejs Application using Sweetalert');
        }
    }
  }
</script>

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>
And the output of the above code is
vue sweetalert examples  popup notification

Modal Examples 

This Below demo covers the following things
  • How to display a successful dialog window? 
  • How to show informational dialog window? 
  • How to display Error dialog window? 
  • Modal window Prompt to take input from the user 
  • Alert display position change 
  • Delete popup notification
<template>
  <div id="app">
   <div> <img alt="Vue logo" src="./assets/logo.png"></div>
    <button v-on:click="displaySimplePopup">Click Me</button>
    <button v-on:click="infoAlert">Info Popup</button>
    <button v-on:click="successAlert">Success Popup</button>
    <button v-on:click="errorAlert">Error Popup</button>
    <button v-on:click="AlertPassingData">Prompt Popup</button>
    <button v-on:click="positionPopup">Custom Position Popup</button>
    <button v-on:click="deletePopup">Delete Popup</button>
  </div>
</template>

<script>
  export default {
    data() {
        return {
          msg:''
        };
    },
    methods: {
        displaySimplePopup(){
            // Use Sweetalert
            this.$swal('Welcome to Vuejs Application using Sweetalert');
        },
        infoAlert() {
            this.$swal({
                type: 'info',
                title: 'Title Info',
                text: 'This is informational message'
            });
        },
        successAlert() {
            this.$swal({
                type: 'success',
                title: 'Title Success',
                text: 'This is successful message'
            });
        },
        errorAlert() {
            this.$swal({
                type: 'error',
                title: 'Error Title ...',
                text: 'Error Occured!',
                footer: '<a href>Please click this for more about this error</a>'
            });
        },
        positionPopup() {
            this.$swal({
                position: 'top-end',
                type: 'success',
                title: 'Data is saved in Database',
              showConfirmButton: false,
              timer: 1000
            });
        },
        deletePopup() {
            this.$swal({
                  title: "Do you want to delete this record",
                  text: "This will be record from Database",
                  type: "warning",
                  showCancelButton: true,
                  confirmButtonColor: "#4026e3",
                  confirmButtonText: "Yes, remove it it!"
                  }).then((result) => { // <--
                  if (result.value) { // <-- if accepted
                          del('status-delete/' + id);
                          }
                  });
        },
          AlertPassingData() {
            this.$swal({
              title: 'Please enter String?',
              input: 'text',
              inputPlaceholder: 'Enter String here',
              showCloseButton: true,

            });
        },
    }
  }
</script>

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>
Output is
vue sweetalert input dialog examples

Placing Html content 

The alert dialog can also provide static content and dynamic content. Dynamic content can be placed using HTML attribute of $swal function. Can also contain HTML custom forms to take input from user Here is an example for HTML content in the Dialog window
<button v-on:click="htmlContentAlert ">Html contentPopup</button>
 htmlContentAlert {
            this.$swal({
   title: "<i>This is title</i>", 
   html: "This is html text: <b>bold</b><i> italic</i>",  
   confirmButtonText: "V <u>Yes</u>", 
});;
},

Ajax demo usage 

This is an example for ajax for asynchronous processing of a request. This shows on loading icon image on loading ajax request processing

   <button v-on:click="ajaxAlert">Ajax Popup</button>

  ajaxAlert() {
            this.$swal({
  title: "Asynchronus example",
  text: "Demo application for ajax example",
  type: "info",
  showCancelButton: true,
  closeOnConfirm: false,
  showLoaderOnConfirm: true
}, function () {
  setTimeout(function () {
    swal("Completed!");
  }, 2000);
});
        },
  
The code for this blog post can be download from here

bLazy.js Lightweight javascript framework for lazy load images, videos,iframes

In this blog post, We are going to learn blazyJS javascript library for loading images.
bLazy.js Lightweight javascript framework for lazy load images

bLazy.js introduction

For any webapplication, Page loading is important factor for better use experience as well as SEO point of view. On any web apage, if any elements or objects like images, or videos  or any HTML element is taking longer time, It will affect the overal page speed of a applicaiton. Blazy Js is a opensource javascript framework that load sthe elements  lazily. instead of eagerly during page loads. Lazy loading works asynchronusly meaning, It loads the elements after the main page is loaded completely This framework will solve the following issues.

Features and advantages

  • Asynchronus loading of images or any elements
  • Serve images based on screen width - Small screen get different images than web images
  • It is simple library and size is 2kb 
  • There is no Jquery dependency
  • It reduces server  bandwidth and overall improve page loading times
  • It works on all latest and old browsers
  • Provided NPM and CDN scripts 
  • It support all types of images including background images 
  • Lazy load all the html elmeents thats use src attbutes like iframe,video,audio, and games

Installation and Usage on html application

There are various ways we can integrate Blazyjs in web application

Including CDN script to Jquery and javascrip based web pages

Script can be download from here or you can include cdn as below
<script src="https://cdnjs.cloudflare.com/ajax/libs/blazy/1.8.2/blazy.min.js"></script> 

NPM Package install for node based applications 

It provides npm package. So you can use npm or bower tools to install into your application.
npm install blazy --save
bower install blazy --save

Initlize and load blazy objects 

First We need to create Blazy object in the script tag of html page

var bLazy = new Blazy({
  //options here
});
Options Container - this option enables to load the images inside scrolling container success callback- this call back will be loaded once successfully loaded images lazyily selector - This is jquery selector kind of syntax. To load all images, Please use img as value for this option.

Examples Usage

How to lazy load images in html page with examples

Image will be displayed on html page using img tag. To make image serving using img tag, add class=".b-lazy" css style to img tag Provide image url in data-src attribute to load asynchronusly
<img class="b-lazy" data-src="image-url" />

How to lazy load background iamges in html page

 Instead of img tag, Use div tag and provide css style to div and provide image url
<div class="b-lazy" data-src="image-url"></div>
The below example explains following things

  • How to lazy load iframe in html page - using b-lazy css style 
  • How to lazy l oad html5 videos 
  • How to lazy load html script 
  • How to serve multiple images lazily

// iframe lazy loading in a page
<iframe class="b-lazy" 
   data-src="video url" 
   frameborder="0" 
   allowfullscreen>
</iframe>
// lazy load videos
<video class="b-lazy" data-src="Video url" controls></video>
//  This explampl explains about how to lazy images  based on 
var bLazy = new Blazy({ 
breakpoints: [{
width: 320 
, src: 'data-src-320 image file'
}
, {
width: 1024 
, src: 'data-src-1024 image file'
}]
});