Showing posts with label Web App Development. Show all posts
Showing posts with label Web App Development. Show all posts

Switch node versions using nvm

 Switch NodeJs versions using nvm


List all nodejs versions available

nvm ls-remote


Install specific version

nvm install 14.18.1


Install latest nodejs

nvm install node


List nodejs versions available in the machine

nvm ls


Switch to nodejs version

nvm use 16.13.0


Uninstall nodejs version

nvm uninstall 16.13.0

Git: Get changes from another branch

 Git: Get changes from another branch 


Suppose you are working branchA and somebody merged changes to main branch. You want pull latest changes from main to branchA.

option 1

git checkout main

git pull

git checkout branchA

git merge main


option 2

git rebase main


option 3

git pull origin main



Git: Save user credentials

 Git: Save Username and Password


To avoid prompting username and password, run below command

git config --global credential.helper store

then

git pull


Reference: https://stackoverflow.com/questions/35942754/how-can-i-save-username-and-password-in-git 

React: File download

 React: File download


Got a requirement to save api response data (blob) to a file.


setLoading(true);
const responseData = await callApi();
setLoading(false);
var blob = new Blob([responseData], { type: "application/json" });
let url = window.URL.createObjectURL(blob);

// Creating the hyperlink and auto click it to start the download
let link = document.createElement("a");
link.href = url;
link.download = "samplefile.json";
link.click();

GIT: Edit last commit message

 GIT: Edit last commit message (not pushed)


git commit --amend -m "New commit message"

Reference
https://stackoverflow.com/questions/179123/how-to-modify-existing-unpushed-commit-messages

React: Preload Images

 React: Preload Images


I had a situation that lot of time taken to load images, which are loaded dynamically. One solution was to preload the images whenever we get the URL so that images will be available in cache and it will load quickly.

Below solution worked

useEffect(()=>{
images.forEach((image) => {
const img = new Image();
img.src = baseurl + image.fileName;
});
}, [])


References:

https://stackoverflow.com/questions/42615556/how-to-preload-images-in-react-js


 

Tailwind CSS: Dark and Light Theme

 Tailwind CSS: Dark and Light Theme 

I am using Tailwindcss in my react app. One of the requirement was to provide light and dark theme for the web app. This can be achieved easily with Tailwind.

1. Specify colours and styles for light and dark theme. For light theme just use class-name as it is and for  dark theme, use dark:class-name.

eg: bg-white dark:bg-gray-700


Switch between white and dark theme

To switch between the themes, there are many methods. I chose using class. Using class, need to mention darkMode: "class" in tailwind.config.js.

/** @type {import('tailwindcss').Config} */
module.exports = {
darkMode: "class",
theme: {
extend: {},
},
plugins: [],
content: ["./src/**/*.{js,jsx,ts,tsx,html}", "./public/index.html"],
};

Then we can add a button, on click add/remove class-name "dark" to/from <html> to toggle between dark between light theme.

document.documentElement.classList.toggle("dark");

or 

document.documentElement.classList.add("dark");
document.documentElement.classList.remove("dark");



Note: To keep the theme selection, we can store the value to localstorage and retrieve it on  load for better user experience.


Reference: https://tailwindcss.com/docs/dark-mode



Git: Pulling is not possible because you have unmerged files

 Git: Pulling is not possible because you have unmerged files


Some times I receive this message because local file file changes conflict and requires merging. To revert local changes  in this scenario, use below command

git reset --hard HEAD

If already committed to local branch and need to revert the last committed changes,

git reset --hard HEAD~1

React Router V6 (react-router-dom) Dynamic Routing

 React Router V6(react-router-dom) Dynamic Routing


I was trying to implement dynamic routing with router v6 similar to that with v4 . 

eg in v4

const routes = [
{ path: '/', key:"home", component: Home },
{ path: 'page1',key:"page1", component: Page1 },
{ path: 'page2', key:"page2" component: Pag2 }
];


<Route path={variable} component 

<Router>
<Switch>
{routes.map(page => (<Route key={page.key} path={page.path} component={page.component} />))}
</Switch>
</Router>

This can be achieved in router v6 using useRoutes

Router.tsx

import { useRoutes } from "react-router-dom";

import Home from "../pages/Home";
import Page1 from "../pages/Page1";
import Page2 from "../pages/Page2";

export default function Router() {
return useRoutes([
{ path: "/", element: <Home /> },
{ path: "/page1", element: <Page1 /> },
{ path: "/page2", element: <Page2 /> },
]);
}


App.tsx

import React from "react";
import { BrowserRouter } from "react-router-dom";
import Router from "./helpers/Router";
function App() {
return (
<div>
<BrowserRouter>
<Router />
</BrowserRouter>
</div>
);
}

export default App;

References:

https://reactrouter.com/en/main/hooks/use-routes


React: Create React App not working in Internet explorer

React: Create React App not working in Internet explorer

I faced this issue today. When I created a new react application using CRA. It was not working in internet explorer browser. I solved it by using polyfills. I followed below steps


1. installed react-app-polyfill

yarn add react-app-polyfill --save


2. imported it in index.js (should be first line)

import 'react-app-polyfill/ie11'; 
import 'react-app-polyfill/stable';

3. Updated browsers in package.json
"browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "ie 11",
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
4. Deleted node_modules 
5 yarn and yarn start. Worked !!!



useSelector useDispatcher React Example

useSelector useDispatcher - React Example

We can use useSelector and useDispatcher instead of using connect().

import React, { useEffect } from 'react';
import { useSelectoruseDispatch } from "react-redux";
import './App.css';

import {dataActionfrom './actions/getDataAction';

function App() {
  
  const data = useSelector(state => state.dataReducer);
  const dispatch = useDispatch();

  useEffect(() => {
    dispatch(dataAction())
  });

  return (
    <div className="App">
      <header className="App-header">
        <h1>{data}</h1>
      </header>
    </div>
  );
}

export default App;

Please find github project - https://github.com/codingtechlife/useSelector_useDispatcher_example


Facebook like skeleton loader in React


Facebook like skeleton loader in React


You have noticed the loader displayed in facebook and other new websites when content is loading. The loader can be implemented in react application using  react-content-loader

demo:  https://danilowoz.com/create-content-loader/

To install:
npm i react-content-loader --save

yarn add react-content-loader


Usage: 
1. Preset Example 

import ContentLoader, { Facebook } from "react-content-loader";
const MyLoader = () => <ContentLoader />;
const MyFacebookLoader = () => <Facebook />;

2. Custom

import React from "react";
import ContentLoader from "react-content-loader";

const CustomLoader = () => (
  <div style={{ width: "100%", minHeight: "500px" }}>
    <ContentLoader style={{ width: "100%", height: "500px" }}>
      <rect x="65%" y="0" rx="5" ry="5" width="100%" height="30" />
      <rect x="10" y="40" rx="5" ry="5" width="100%" height="40" />
      <rect x="10" y="100" rx="5" ry="5" width="100%" height="30" />
      <rect x="10" y="150" rx="5" ry="5" width="100%" height="30" />
      <rect x="10" y="200" rx="5" ry="5" width="100%" height="30" />
      <rect x="10" y="250" rx="5" ry="5" width="100%" height="30" />
      <rect x="10" y="300" rx="5" ry="5" width="100%" height="30" />
      <rect x="10" y="350" rx="5" ry="5" width="100%" height="30" />
      <rect x="10" y="400" rx="5" ry="5" width="100%" height="30" />
      <rect x="75%" y="450" rx="5" ry="5" width="100%" height="30" />
    </ContentLoader>
  </div>
);
export default CustomLoader;

Note: I have faced issue in providing 100% width for the loader. The above code fixed issue and take 100% width of the container.

create-react-app - Create ReactJs Application Tutorial

create-react-app - Create ReactJs Application Tutorial


I have been trying to learn ReactJs and create some sample applications with it. Today found create-react-app (https://github.com/facebookincubator/create-react-app) which will help us to generate sample reactjs application without knowing the reactjs. Only thing we need to do are,

1. Install latest nodejs version.

2. Install create-react-app
npm install -g create-react-app

3. Generate reactjs application using create-react-app
create-react-app myApp

4.       Run the application
cd myApp
npm start

The application will be started at http://localhost:3000.



Make javascript execution synchronus - A Scenario in Angularjs

Make Javascript Execution Synchronous - A Scenario in Angularjs

Last week I came to deal with a problem in my angularjs application. I want to execute a code block only after getting the response from rest service call. This code block is not inside success/failure call back function, but it is below service call code as below.

function function1() {
//rest call
dataService.serviceCall().then(function (data) {
            console.log("label a")
            }, function (error) {
                console.log("call failed"+ error);
                
            });
            
  console.log("label b")
 }

I want to print "label b" only after printing "label a". But now, as javascript is asynchronous, 'label b' is first printed then 'label a'. It is not waiting for the response of the service call.

To print "label b" only after printing "label a", I found two solutions,
1.  Put the label a code inside callback function.
eg :  
function1() {
//rest call
dataService.serviceCall().then(function (data) {

                 console.log("label a");
                printB();
                
            }, function (error) {
                 console.log("call failed"+ error);
             });
            var printB = function(){
                console.log("label b");
            }
        }
In real case, the code block was not a single line code, that's why /i put it outside service call. If it is a small one i could have been included in success callback function it self. Here I moved all the code into a new function in side function itself, so that I will get the all local references. Then I called function inside success callback function. 

I added a new function syncCall. This will call function1. Js promises or deffered is used to make it synchronous. If response is received successfully, 'label a' is printed, promise is resolved and returned. On successful resolution of promise, 'label b' is printed.
eg: 

syncCall();

        function syncCall() {
            var deferred = $q.defer();
            function1(deferred).then(function () {
                console.log("label b");
            }, function () {
                console.log("err");
            });
        }

        /* Filter items */
        function function1(deferred) {
dataService.serviceCall().then(function (data) {

                 console.log("label a");
                deferred.resolve();
                
            }, function (error) {
                 console.log("call failed"+ error);
                deferred.reject();
             });
      return deferred.promise;
        }


AngularJS Prevent Event Propagation Click Example

AngularJS Prevent Event Propagation Click Example

Today I was stuck with a problem in angularjs. I have a table row and a button in table cell. I have bound event event for both table row and button. So I have to disable event on table row click when I click on button, in other words I have to stop propagation of event on button click.

I found a solution as below,

<a href="#" ng-click="functionName(); $event.preventDefault(); $event.stopPropagation();">


$event.stopPropagation(); alone was not working. When I used $event.stopPropagation(); alone, on click it was redirecting to some other page. When I tried adding  $event.preventDefault(); $event.stopPropagation();. It worked.

Reference:
http://stackoverflow.com/questions/10931315/how-to-preventdefault-on-anchor-tags

Yeoman - Create an AngularJs Scaffold

Yeoman - Create an AngularJs Scaffold


Introduction
Yeoman is used to generate a basic scaffolding of app. This will help to start a new project quickly, creating folder structure and configuration, adding necessary libraries/tools like bootstrap, sass etc. and prescribing best practices. There are generators associated with yo for different languages like angular, backbone, etc.

Environment setup and Installation
1. Pre-requisites:

  • Node.js v0.10.x+
  • npm (which comes bundled with Node) v2.1.0+
  • git

2.Install yo, bower and grunt
   C:\>npm install --global yo bower grunt-cli

3. Install generator-angular and generator-karma using this command:
   C:\>npm install --global generator-angular@0.11.1 generator-karma

Generate Angular App
Create a folder for app,
  C:\>md yApp
  C:\>cd yApp

Now access generators via the Yeoman menu,
  C: \yApp>yo


Select Angular as generator.  On selecting angular, it will ask whether to include different components like Sass, bootstrap and different angular-modules.


On hitting enter key, different modules will be installed and app will be generated. We can edit this app and develop our app. Like we can add new controller in controller folder, add new view in views folder. Also add other libraries using bower.


Run App: Start Server
Use below command to run grunt task to start Node-based http server on localhost:9000.
C:\yApp>grunt serve


Run Unit Tests-Using Karma and Jasmine
The Angular generator has included two test frameworks: ngScenario and Jasmine. A test directory is created in the root folder, creates test spec files, created a karma.conf.js file, and pulled in the Node modules for Karma while generation of app. Add/Edit spec file for testing different modules. Use below command to run unit tests.
C:\yApp>grunt test

Get production app: Minification and Uglification
Concatenate and minify our scripts and styles to save on those network requests, run unit tests, optimize images if we were using any, etc. are one to make the code production ready using the command below,
C:\yApp>grunt

AngularJS Sort and Search in Table

AngularJS Sort and Search in Table

Today I have implemented sort and search functionality for table, just like jquery datatable, referring a tutorial on scotch.io. It is easy to implement.

https://scotch.io/tutorials/sort-and-filter-a-table-using-angular

Yeoman bootstrap styling not coming for angular generator

Yeoman - AngularJS Generator Bootstrap Styling Issue

I have created an angular project using yeoman angular generator with bootstrap. After generating the scaffold app, I observed that bootstrap was not added successfully even though i have selected to add bootstrap during the generation of scaffolding. The issue has been solved by manually adding the bootstrap in bower.json or installing bootstrap manually.

bower install --save bootstrap#3.3.4
grunt serve

Reference:
http://stackoverflow.com/questions/30946498/yeoman-and-bower-not-adding-bootstrap-css-angular-generator



Print Functionality For Web App

The Print Functionality on a Webpage

Today I have to deal with print functionality for a web page. Apart from Ctrl+P there are things to be taken care for printing, why need for a "print this page" button.

For printing, the pages should not be like webpage we see. The menus and other unwanted items can be avoided. The entire webpage will be divided into many pages. The page layout can be changed. Images and coloring can be changed. Typography can be changed.

The print function can be achieved using window+print();, http://jsfiddle.net/35vAN/ looks very interesting

You might have seen "print this page" button in web pages. Upon clicking this will convert the page so that it will be convenient for taking hard copies. Print page can be converted effectively using print styles. For responsive web design, this is not much applicable since the layout changes according to the screen size.