Search

Instal React Js on Windows

In this tutorial, we will learn how to install React.js on Windows.React.js is a library which helps us to build and create front end interfaces for Single page applications and it utilises the power of virtual DOM.React.js was an inhouse project of Facebook, and it was made open to the public in the year 2013. The adoption of React.js has seen an upward curve since its avantages have been realized. Various startups and established organizations are now adopting the technology and upgrading their technology stack.1. Prerequisite for WindowsTo install React on Windows, your system will require the minimum configuration as below:Windows XP, Windows 7 (32/64 bit) or higherMinimum 4 GB RAM and higher10 GB available space on the hard diskAt least one Internet Browser e.g. Chrome, Firefox, Microsoft Edge etc.Node.jsActive internet connection minimum speed 512kbps and above.At least one installed code Editor to test and debug your code e.g.  AtomSublimeVisual studio code2. Introduction to React.jsReact.js is a library written in TypeScript. It utilises the syntax of the modern version of JavaScript as described by ES6 and its higher version.Applications built using React.js use the Single reusability principle. This advocates the idea of building web pages and applications using components and unidirectional flow. In React.js we have the concept of states and the concept of immutability. Components have hierarchy in terms of Parent and Child components. A component in case of React.js can be thought of as a piece of code which is based on the principle of pure functions. We will look into the pure component later. First, let’s understand what a state is. For e.g. To become a member of a service, the user fills his information on the registration page. While filling the details there can be many states of the form, for e.g. When the form field is empty or when the form field has witnessed some error on some particular field, which needs to be corrected; or when after correction, the form data has been validated and is ready for submission. So, at a broad level, the registration form has been through various states. These states represent at which level the application is, in terms of interacting with the end-user. Each level of interaction for this form is represented by the state, from an empty form to being a fully filled form with a display of an error for certain fields and the validated form. In React.js, we have the component based on the pure function. A pure function can be memorised as a piece of code, which does one task and does it pretty well. For a certain input, it always returns the same output, so this means we are increasing predictability of the code. Since React.js follows a certain code pattern and principles in order to work, it lowers the curve of the knowledge gap; whether you are one-person or a team of developers working mutually.3. Introduction to Node.js and NPM on WindowsTo run React.js we will require Node.js on our system.Node.js is a server which will help us to run the React.js code.It is based on non-blocking input and output and the Chrome V8 JavaScript engine. The Node.js code is open source.NPM which is an abbreviation of Node package manager, npmjs.com is supported by various developers around the world. It has various node modules, using which developers can host and publish their modules on the open-source community.  It hosts modules in private and public visibility.A module carries code which exists to serve high or low level functionalities. In terms of code adoption and availability of various modules it gives an edge and tries to make the developer more productive.  We can plug in and plug out the module. Some modules are dependent on other modules; which is defined as dependency among modules.While building an application, a developer can pick the module, tweak and remix it to suit the application needs, and can then release to the open-source community. So, instead of reinventing the wheel, it is like picking a wheel (npm module) from npmjs.com, giving it further momentum and giving it back to the open source community.4. Download and Install Node.jsTo install Node.js we need to go to the URLDepending upon our Windows OS version in terms of 32 Bit or 64 Bit, we can pick the installer and install that version.  In this tutorial I am using Windows 8, 64 Bit.  The Node.js installer includes NPM. It is best to install the even numbered version of NPM.Depending upon your operating system, the Nodejs.org home page will show the Download button and recommended LTS version.After the download is complete we will go to the downloads folder and run the installer.The installer will show the below Setup Wizard. Click next.The next screen will ask for the End-user License Agreement. Select the checkbox at the bottom right to provide your consent and click on Next to proceed with the installation.The installer will ask for Destination folder and the default path set by installation is C:\Program Files\nodejs\Click on Next buttonThe above screen is an important step in the installation process. And if you see closely it also sets the environmental path variables to command prompt on Windows.Click on Next to continue with the installation.The Windows OS may ask you to allow Node.js installation and make changes.Click on Yes button.During the installation, if you have allowed for Chocolatey and required modules installation for C++ and Python, you will see the UI below in the command prompt. This installation requires 3 Gb of free disk space. In this tutorial this step is not required, so we are skipping this step by closing the window.If you are interested in installing it, press Enter to continue.Once the istallation is complete you need to verify the Node.js installation.  For this we will use the command prompt.To run command promptPress keys Win+RAnd type cmd in the window below.Next Click on Ok or Press Enter on the keyboard.5. Installation of ReactAfter installation of Node.js we need to install React. To check the Node.js version, open the Windows command prompt. Press Win+R and type cmd. In the command line, type   node -v to see its version. We can also check for npm version, which is installed with Node.js, with the following command npm -v After running these commands, we can check the node version v14.15.1 and npm version 6.14.8As we have confirmed the Node.js installation we can proceed to the next steps.While in the command prompt, we have navigated to a folder called Codefactory by following the command cd CodefactoryIn this folder we have created a folder  called react-windows by using the command mkdir react-windows.After the folder react-windows has been created, we will change the directory to react-windows with the command cd react-windows React.js can be installed in various ways. Now, we will type npm init. It will ask for the below configuration line by line. Insert your input, followed by Enter keypress to proceed with the next configuration.   At the end of the configuration it will confirm for the inputs you have entered. If you are happy with the configuration data, type yes and enter to continue.The npm init will help us to create a package.json file.Now, the next step to install React.js requires us to go to the command prompt and type the following command in the react-windows directory.npm install --save reactAnd after the above command npm install --save react-domBehind the scene, these commands fetch the specified module from npmjs.com and download it in the local codebase.Let's have a look at the react-windows folder. Here we can see some newly created directories in node_modules.So, in this tutorial, we have learned to install React and reactDOM. But to see the React.js SPA (single page app) there is more work to be done in the above code.As an alternative and fast approach we can do it via create-react-appLet us move to Codefactory folder and with the command cd.. create another folder react-cliNext, type the following command mkdir react-cliNow we will use create-react-app module and type the following commandPlease note that my-fast-app is the name of your app. This is an example and you can be creative in choosing your own name.npx create-react-app my-fast-appIf we see closely it will take care of the rest of the installation steps, and react, react-dom and other related modules are installed automatically.This process is a little data intensive, so please be patient while the download and installation happensWhen the above step gets completed the command prompt displays the below output.Now, let us run our first react app, by navigating to my-fast-app directory as belowcd my-fast-appAnd enter the next command as npm startThe npm command will show the application in the browser. http://localhost:3000And if you are running node.js for the first time using npm command, it will ask for permission to allow access and we need to allow access to run.As we are using a code editor we can have a look at the directory structure and some of the important files, such as index.html in the public folder, in src folder the index.js and App.js. The src folder contains the react component which we can build further on this codebase. index.js is the js invocation point for react app.This index.js is linked with the App.js, which is responsible for showing the content in the browser. That’s what we see on the demo page.Let’s edit the App.js by going to line 10 and adding the following codeTalk is cheap, show me the <code>Code</code>Once you save the file by Ctrl+SThe code will be auto refreshed in the browser, after compiling.It will show us the following output.So, now feel free to change messages and alter the page layout and structure for  experimentation.If you are familiar with CSS, you may also change the page style using App.css and tinker with the code as well.SummaryIn this tutorial, we have introduced you to React.js . Its impact in terms of building modern front end interfaces using component-based architecture is significant. We have also touched upon the concept of states, immutability and pure functions.We have got a brief introduction to the Node.js server and NPM modules, the capabilities of Node.js server and the power of the open source community in the npmjs.com.To install React, Node.js installation is a prerequisite.There are various methods for installation. Once we have installed Node.js, React can be installed either by npm commands or by using the create-react-app module.

Instal React Js on Windows

5K
Instal React Js on Windows

In this tutorial, we will learn how to install React.js on Windows.

React.js is a library which helps us to build and create front end interfaces for Single page applications and it utilises the power of virtual DOM.

React.js was an inhouse project of Facebook, and it was made open to the public in the year 2013. The adoption of React.js has seen an upward curve since its avantages have been realized. Various startups and established organizations are now adopting the technology and upgrading their technology stack.

1. Prerequisite for Windows

To install React on Windows, your system will require the minimum configuration as below:

  1. Windows XP, Windows 7 (32/64 bit) or higher
  2. Minimum 4 GB RAM and higher
  3. 10 GB available space on the hard disk
  4. At least one Internet Browser e.g. Chrome, Firefox, Microsoft Edge etc.
  5. Node.js
  6. Active internet connection minimum speed 512kbps and above.
  7. At least one installed code Editor to test and debug your code e.g.  

2. Introduction to React.js

React.js is a library written in TypeScript. It utilises the syntax of the modern version of JavaScript as described by ES6 and its higher version.

Applications built using React.js use the Single reusability principle. This advocates the idea of building web pages and applications using components and unidirectional flow. In React.js we have the concept of states and the concept of immutability. Components have hierarchy in terms of Parent and Child components. A component in case of React.js can be thought of as a piece of code which is based on the principle of pure functions. We will look into the pure component later. First, let’s understand what a state is. For e.g. To become a member of a service, the user fills his information on the registration page. While filling the details there can be many states of the form, for e.g. When the form field is empty or when the form field has witnessed some error on some particular field, which needs to be corrected; or when after correction, the form data has been validated and is ready for submission. So, at a broad level, the registration form has been through various states. These states represent at which level the application is, in terms of interacting with the end-user. Each level of interaction for this form is represented by the state, from an empty form to being a fully filled form with a display of an error for certain fields and the validated form. In React.js, we have the component based on the pure function. A pure function can be memorised as a piece of code, which does one task and does it pretty well. For a certain input, it always returns the same output, so this means we are increasing predictability of the code. Since React.js follows a certain code pattern and principles in order to work, it lowers the curve of the knowledge gap; whether you are one-person or a team of developers working mutually.

3. Introduction to Node.js and NPM on Windows

To run React.js we will require Node.js on our system.Node.js is a server which will help us to run the React.js code.It is based on non-blocking input and output and the Chrome V8 JavaScript engine. The Node.js code is open source.

NPM which is an abbreviation of Node package manager, npmjs.com is supported by various developers around the world. It has various node modules, using which developers can host and publish their modules on the open-source community.  It hosts modules in private and public visibility.A module carries code which exists to serve high or low level functionalities. In terms of code adoption and availability of various modules it gives an edge and tries to make the developer more productive.  

We can plug in and plug out the module. Some modules are dependent on other modules; which is defined as dependency among modules.

While building an application, a developer can pick the module, tweak and remix it to suit the application needs, and can then release to the open-source community. So, instead of reinventing the wheel, it is like picking a wheel (npm module) from npmjs.com, giving it further momentum and giving it back to the open source community.

4. Download and Install Node.js

To install Node.js we need to go to the URL

Instal React Js on Windows

Depending upon our Windows OS version in terms of 32 Bit or 64 Bit, we can pick the installer and install that version.  

In this tutorial I am using Windows 8, 64 Bit.  

The Node.js installer includes NPM. It is best to install the even numbered version of NPM.

Depending upon your operating system, the Nodejs.org home page will show the Download button and recommended LTS version.

After the download is complete we will go to the downloads folder and run the installer.

The installer will show the below Setup Wizard. Click next.

Instal React Js on Windows

The next screen will ask for the End-user License Agreement. Select the checkbox at the bottom right to provide your consent and click on Next to proceed with the installation.

Instal React Js on Windows

The installer will ask for Destination folder and the default path set by installation is C:\Program Files\nodejs\
Click on Next button

Instal React Js on Windows

Instal React Js on Windows

The above screen is an important step in the installation process. And if you see closely it also sets the environmental path variables to command prompt on Windows.

Click on Next to continue with the installation.

The Windows OS may ask you to allow Node.js installation and make changes.Click on Yes button.

Instal React Js on Windows

During the installation, if you have allowed for Chocolatey and required modules installation for C++ and Python, you will see the UI below in the command prompt. This installation requires 3 Gb of free disk space. In this tutorial this step is not required, so we are skipping this step by closing the window.

If you are interested in installing it, press Enter to continue.

Instal React Js on Windows

Once the istallation is complete you need to verify the Node.js installation.  

For this we will use the command prompt.

To run command prompt

Press keys Win+R

And type cmd in the window below.

Next Click on Ok or Press Enter on the keyboard.

Instal React Js on Windows

5. Installation of React

After installation of Node.js we need to install React. To check the Node.js version, open the Windows command prompt. 

Press Win+R and type cmd. 

In the command line, type   

node -v to see its version. 

We can also check for npm version, which is installed with Node.js, with the following command 

npm -v 

After running these commands, we can check the node version v14.15.1 and npm version 6.14.8

Instal React Js on Windows

As we have confirmed the Node.js installation we can proceed to the next steps.

While in the command prompt, we have navigated to a folder called Codefactory by following the command cd Codefactory

In this folder we have created a folder  called react-windows by using the command mkdir react-windows.Instal React Js on Windows

After the folder react-windows has been created, we will change the directory to react-windows with the command 

cd react-windows 

React.js can be installed in various ways. 

Now, we will type npm init. It will ask for the below configuration line by line. 

Insert your input, followed by Enter keypress to proceed with the next configuration.   

At the end of the configuration it will confirm for the inputs you have entered. If you are happy with the configuration data, type yes and enter to continue.

Instal React Js on Windows

The npm init will help us to create a package.json file.

Instal React Js on Windows

Now, the next step to install React.js requires us to go to the command prompt and type the following command in the react-windows directory.

npm install --save react

Instal React Js on Windows

Instal React Js on Windows


And after the above command npm install --save react-dom

Instal React Js on WindowsBehind the scene, these commands fetch the specified module from npmjs.com and download it in the local codebase.

Let's have a look at the react-windows folder. Here we can see some newly created directories in node_modules.

Instal React Js on Windows

So, in this tutorial, we have learned to install React and reactDOM. 

But to see the React.js SPA (single page app) there is more work to be done in the above code.

As an alternative and fast approach we can do it via create-react-app

Let us move to Codefactory folder and with the command cd.. create another folder react-cli

Next, type the following command mkdir react-cliInstal React Js on WindowsNow we will use create-react-app module and type the following command

Please note that my-fast-app is the name of your app. This is an example and you can be creative in choosing your own name.

npx create-react-app my-fast-app

If we see closely it will take care of the rest of the installation steps, and react, react-dom and other related modules are installed automatically.

This process is a little data intensive, so please be patient while the download and installation happens

Instal React Js on Windows


When the above step gets completed the command prompt displays the below output.

Instal React Js on Windows

Now, let us run our first react app, by navigating to my-fast-app directory as below

cd my-fast-app

And enter the next command as npm startInstal React Js on Windows

The npm command will show the application in the browser. http://localhost:3000

And if you are running node.js for the first time using npm command, it will ask for permission to allow access and we need to allow access to run.

As we are using a code editor we can have a look at the directory structure and some of the important files, such as index.html in the public folder, in src folder the index.js and App.js. The src folder contains the react component which we can build further on this codebase. 

index.js is the js invocation point for react app.This index.js is linked with the App.js, which is responsible for showing the content in the browser. That’s what we see on the demo page.

Instal React Js on Windows

Let’s edit the App.js by going to line 10 and adding the following code

Talk is cheap, show me the <code>Code</code>

Once you save the file by Ctrl+S

The code will be auto refreshed in the browser, after compiling.

Instal React Js on Windows

It will show us the following output.

So, now feel free to change messages and alter the page layout and structure for  experimentation.

If you are familiar with CSS, you may also change the page style using App.css and tinker with the code as well.

Instal React Js on Windows

Summary

In this tutorial, we have introduced you to React.js . Its impact in terms of building modern front end interfaces using component-based architecture is significant. We have also touched upon the concept of states, immutability and pure functions.

We have got a brief introduction to the Node.js server and NPM modules, the capabilities of Node.js server and the power of the open source community in the npmjs.com.

To install React, Node.js installation is a prerequisite.

There are various methods for installation. Once we have installed Node.js, React can be installed either by npm commands or by using the create-react-app module.

Gaurav

Gaurav Mishra

Author

Gaurav Mishra is an expert in user-interface development and user-experience design, with more than 13+ years of experience. Comfortable to work with any kind of technology, he has growth mindset and keep a beginner mind. He has provided workshops and training in UI development, UX design, and Drupal. He has mentored and trained various students around the world. Gaurav has played the key role in the success of many organizations and likes to build products and services from scratch which delight people.  He likes to challenge the status quo to bring out the best from team & reshape the organisation culture. He likes all genres of music, from Indian classical to club music. 

Join the Discussion

Your email address will not be published. Required fields are marked *

Suggested Blogs

What are React Component Lifecycle Methods

React is the most popular JavaScript library used to create interactive UI for web applications. It is a component-based library where different parts of a webpage can be encapsulated by components which are quite easy to create, manage and update. React allows us to create Single Page Applications which maintain the state of individual components on an app without having to reload it.  What are React Components? Developers who are new to JavaScript libraries and frameworks like React and Angular might ask the question, “What is a component?” Well, in very simple words, a component is a unit of code which includes JavaScript and HTML to build a part of a web page. It acts like a custom HTML element. It is reusable and can be as complex as you want it to be. For example, imagine that you are creating a very basic application with header, footer, and body. The header can be a component; the footer can be another component and the body can be yet another one or even might consist of multiple components.One of the most useful characteristics of React is its ability to integrate reusable components in a project. Reusability is the characteristic of a component which allows it to be used again, thereby reducing the amount of code a developer has to write. In our example here, the header can be a reusable component and can be used on all the pages of the application, which makes it easy to maintain and update. What does a component look like? Here is a simple example of a react component which contains a simple form. This is a class-based component. React also supports function-based components. As you can see in the code below, App is a user-defined class which inherit from React’s Component class and it has a render method which returns HTML code. As the name suggests, the render method returns and renders HTML to our browser. Every component has to return HTML which is rendered to the user’s browser by render method.import React, { Component } from 'react';  class App extends Component {    handleChange(event) {      this.setState({value: event.target.value});    }    render() {      return (                              Username:                                            Password:                                              );    }  }    export default App; In the above example, we have created a login form where there are 2 input boxes for the user to enter their username and password and then submit the form. We have assigned an event handler to form which will handle the login event in component.We have exported our component (using export default App) so that it can be rendered inside other components.This is a very basic example of component, but this can be as complex as you want it to be. But it is always advised to make your component independent and it should represent only a part of your page which can be reusable as well. It can return complex HTML included with JavaScript to handle complex features in your application.Component as a class React allows us to create component in the form of class as well as functions. While creating component as class you need to define a class which extends React.Component class. Component class has many features which the deriving class can use to maintain the state throughout the lifecycle. In case you want to have more custom features, you can create your own base component class which derives from Component class, and then your component classes can derive from your base component class. What do we mean by Component Lifecycle?Lifecycle of a component is the set of different stages (also known as lifecycle hooks) a component goes through while it is active. Stages could be when a component is created or when any changes are made to the component and many others. There are different methods executed by React at different points of time between when a component is created and at the end when it is destroyed and not in use. One such hook or method we have already seen in the code above, which is render(), and it is executed by React to render the component. We can override these methods and perform certain tasks in those methods, but every lifecycle serves a different purpose and it can be a nightmare if we ask them to do something that they aren’t supposed to or are not very good at. As a developer we should be aware of what those different stages are, what happens in those stages, in what order they execute and how we can make the best use of it. Understanding the lifecycle of components also helps us predict behavior of a component at different stages, which makes it easier to work with them. Managing a large set of components in an application can get you in trouble if you do not know how they work behind the scenes.Props and State Before we start with lifecycle hooks, lets understand what props and state are as they are most commonly used properties in component classes. Props It is a keyword which means properties. Props are used by callers of components to pass properties to the called component in a uni-directional flow. For example, if Parent component renders child component, it can define props and pass them to the child component which is then available and accessible by this.props. Another thing to note here is that props is a ready-only attribute which means data which is passed by parent should not be changed by client components. State State is a plan JavaScript object which defines the current state of any component. It is user defined and can be changed by lifecycle hooks. Ideally state should contain only data which is going to be rendered on DOM. State has getter and setter methods this.getState() and this.setState() which as the names suggest are used to access and update State. It is good practice to use setState method to update State and treat State as an immutable JavaScript object.Since there are many lifecycle hooks a component goes through, it would easier to understand if we start with the hooks which are executed when a component is created.Lifecycle hooks while Mounting [These lifecycle hooks are executed in order as listed, when a component is created]constructor(props) This is not a component lifecycle hook, but it is important to mention here and to be aware that Constructor is executed before it is mounted. Constructor receives props(properties of a component) as an argument which then can be passed to base class using super keyword if we define the constructor.  It is not mandatory to define constructor in component class, but if you do to perform any logic, then you need to call base constructor using super keyword.  Mainly constructors are used: To Setup local state of component with this.state To bind event handler methods. This is what a simple constructor would look like.import React, { Component } from 'react';  class App extends Component {    constructor(props) {      super(props);      this.state = { value: 0 };      this.handleClick = this.handleClick.bind(this);    }  } this.state should be called only inside constructor, to update the state in other methods use this.setState() method.  If constructor is required to do any heavy tasks, it will impact the performance of component, and you should be aware of this fact.  getDerivedStateFromProps(props, state) After constructor, this lifecycle hook is called before render method is executed. It is called while mounting as well as whenever props have changed. This is not very commonly used, only in cases where props can change, and you need to update state of the component. This is the only use case where you should implement this lifecycle hook.This method is executed on every render and cannot access component instance.import React, { Component } from 'react';  class App extends Component {    getDerivedStateFromProps(props, state) {      if (props.value !== state.prevValue) {        return {          prevValue: props.value        };      }      return null;    }    }render() This is the method which is required to be implemented in component class. It can access props and state. This is where you can write your html and jsx code. You can also render child components in this method which will then be rendered as well. Before completing the lifecycle of parent, lifecycle of all child components will be finished. All this html and jsx is then converted to pure html and outputs in DOM. JSX is a JavaScript extension which creates React elements. It looks more like template language but it is empowered by JavaScript which allows it to do a lot more. It can embed expressions . JSX has different set of attributes than what we have in html. For example, while creating html using JSX you need to use attribute “className” instead of class. This is what a typical render method looks like:import React, { Component } from 'react';   class App extends Component {   render() {         return (        Click to go Home { this.state.home }       Go to Home         );   } } Alternatively you can also use React.createElement() method to create html using JSX.const element = React.createElement(       'h1',       {className: 'hello'},       'Hello, world!'     );componentDidMount() As the name suggests, componentDidMount() is invoked after the component is mounted, which means html has been added to DOM tree. It is a very commonly used lifecycle hook, as it allows you to do a lot of things including causing side-effects, setting up any subscriptions, or loading data from external endpoints. If you setup any subscription using this method, make sure to unsubscribe them in componentWillUnmount() lifecycle hook. You shouldn’t update state in this method using this.State() as it may cause performance issues. For assigning initial state you should use constructor(). import React, { Component } from 'react';  class App extends Component {    componentDidMount(){    // Component is rendered and now external calls can be made.      this.getDataAfterTimeOut();    }    getDataAfterTimeOut(){      setTimeout(() => {        this.setState({          data: 'Data is fetched'        })      }, 1000)    }  } Lifecycle hooks while Updating [Next set of lifecycle hooks are executed while a component is updating which can be caused by changes to props(properties) or state of component. These are invoked in order as listed below.] getDerivedStateFromProps(props, state) We have already talked about this. This is invoked every time a component is changed or updated. Any changes in properties or state which causes the component to be changed will invoke this method. shouldComponentUpdate(nextProps, nextState) shouldComponentUpdate() is invoked before rendering (not on initial rendering) but only when props or state has been changed. Even though it is not recommended you can use this lifecycle hook to control the re-rendering. This can lead to performance issues as well as bugs, so be careful while doing that.  In this method nextProps can be compared with this.props and nextState can be compared with this.state. This method can return true or false depending on whether you want to continue rendering by skipping the next lifecycle hooks. In either case it can’t prevent re-rendering of child components. Note that this method defaults to true which will not skip rendering and next lifecycle hooks and continue with execution. import React, { Component } from 'react';  class App extends Component {    shouldComponentUpdate(nextProps, nextState) {  // This value will determine if lifecycle execution is to be skipped or continued.      return nextProps.value != this.props.value;    }  } render() After shouldComponentUpdate lifecycle hook render is called, which we have already talked about, it prepares html and jsx code which then outputs to DOM. getSnapshotBeforeUpdate() getSnapshotBeforeUpdate() is invoked right before the recent changes are added to DOM. This lifecycle hook gives us an opportunity to capture any details we need from the DOM before it is updated with new content. For example, if you want to know the scrolling position of the user, which should be restored after the DOM has changed. Use cases for this lifecycle, while rare, can be of great value at times. The snapshot value which is captured and returned by this hook is passed as a parameter to another lifecycle hook componentDidUpdate() which we will talk about next. import React, { Component } from 'react';  class App extends Component {    getSnapshotBeforeUpdate (prevProps, prevState) {  // implementing this method here allows us to capture the snapshot of current dom tree.      if (this.state.value != prevState.value) {        return table.scrollHeight - table.scrollTop      }      return null    }  }componentDIdUpdate(prevProps, prevState, snapshot) componentDidUpdate is invoked when DOM is updated. It is only called on update, not on initial rendering. You can use this method to make data requests after checking if props have changed. You can also call setSatate() in this method, but make sure to wrap that in a condition else it will cause an infinite loop forcing re-rendering and affecting performance issues. Also it should be noted that value for snapshot will only be available if you have implemented getSnapshotBeforeUpdate() in your component; else value for snapshot will be undefined. Here is an example of componentDidUpdate. This is a very basic example where we have captured snapshot by implementing get Snapshot Before Update lifecycle hook. After that componentDidUpdate is invoked and content is overwritten with new dataimport React, { Component } from 'react';  class App extends Component {    getSnapshotBeforeUpdate(prevProps, prevState) {  // implementing this method here allows us to capture the snapshot of current dom tree.      document.getElementById("divContent").innerHTML =      "Before the update content is " + prevState.content;    }    componentDidUpdate(prevProps, prevState, snapshot) {  // You can access snapshot here to get data from dom before it was updated.      document.getElementById("divContent").innerHTML =      "New content updated " + this.state.content;    }  } import React, { Component } from 'react';  class App extends Component {    getSnapshotBeforeUpdate(prevProps, prevState) {  // implementing this method here allows us to capture the snapshot of current dom tree.      document.getElementById("divContent").innerHTML =      "Before the update content is " + prevState.content;    }    componentDidUpdate(prevProps, prevState, snapshot) {  // You can access snapshot here to get data from dom before it was updated.      document.getElementById("divContent").innerHTML =      "New content updated " + this.state.content;    }  } UnMounting [This is where lifecycle of a component ends when component is destroyed and removed from DOM. While Unmounting React gives us an opportunity to do something before component is destroyed, it can include clearing objects which have occupied memory to avoid memory leaks.] componentWillUnMount() componentWIllUnMount() is executed right after component is unmounted which means it is removed from DOM and destroyed. But before it is removed and destroyed, React gives us an opportunity to perform any cleanup we want to. For example, you might have setup subscriptions initially in componentDidMount() which you should unsubscribe when component is destroyed to avoid memory leaks in your application. You can also remove event listeners which were subscribed before. In this lifecycle hooks you should not update state of your component because component is not going to re-render now.import React, { Component } from 'react';  class App extends Component {    componentWillUnmount() {  // Component will be removed from DOM now.        // Unscubscribe subscriptions and events here.  document.removeEventListener("click", this.handleSubmit);    }  }Conclusion In this article we talked about React, its components and its different lifecycles. It is very crucial to understand the different opportunities that React provides through these lifecycle methods. There are many rules we need to follow while working with these hooks. Making them do something they can’t handle can cause performance issues or even infinite loops at times.  These lifecycle hooks work with props and state which are the most used properties of component class. Changes in state and props trigger different lifecycle hooks and even re-render the dom which is something you should be aware of. These lifecycle hooks are provided to intercept the different stages a component goes through and make the best use of it, but without understanding how they work it can break your application by causing performance issues or memory leaks. Hope this has been helpful. 
9270
What are React Component Lifecycle Methods

React is the most popular JavaScript library us... Read More

What are the Pros and Cons of React

If you are a web developer, you are a JavaScript developer--by choice or by force. I mention by force because not many web developers like to work with vanilla JavaScript, especially ones who have worked with frameworks and languages where Object Oriented concepts are made easier for developers to work with. But this does not stop JavaScript from becoming the most widely used language in the world. The popularity of JavaScript has been growing rapidly over the past years.  For any web development, a lot of the work gets done by JavaScript at the user’s browser and at times it becomes difficult to manage vanilla JavaScript in large applications as it lacks the structure which developers enjoy in languages like Java, C# at the back end. Technology leaders identified this problem, and they came up with multiple solutions to make JavaScript not just easier to work with but also to give it performance boost and empowering browsers to do lot more without having to worry about managing complex state of applications as they grow to meet customer demand. React is one such solution along with Angular and Vue. What is React JS? ReactJS is a component-based JavaScript library created by Facebook. React makes it easier to create interactive UI using components and efficiently manage states of those components. Multiple components can be composed together to make complex applications without losing their state in DOM.  Even though we are talking about React as a tool for web application here, it can also be used for mobile application development with React Native, a powerful and open-source native library for mobile application. This is how a simple React component looks like. class HelloWorld extends React.Component {    render() {      return (                  Hello world!              );    }  } What can we build using React JS? Being one of the most popular JavaScript libraries, React can be used to create anything you see on the web. It can be used for multiple requirements; be it a simple but interactive app like Instagram, or a complex streaming app with large userbase and support for multiple languages and regions like Netflix or an application like Facebook, with very large dataset and high complexity with the power to process more than a billion users’ requests parallelly. However, it is not just limited to highly scalable web applications, and you can also create mobile applications using React Native which is an open-source mobile application framework. You can create Android, iOS and Windows apps using this framework. In fact, the above-mentioned web applications “Instagram, Facebook, Netflix” mobile apps are also created using React Native. It gives developers a rich library to utilize the native features of a device to deliver high performance and highly interactive applications to users across the world. Pros 1. Component based architectureIt is not uncommon for vanilla JavaScript based apps to get into a stage, when managing state of data at user’s browser becomes a headache for developers. As the data and complexity of an application grow, it becomes difficult to maintain using vanilla JavaScript. The introduction of React components brings a highly sophisticated unit of a web page which can be independently created, maintained, and even reused. You can divide your web page into multiple components, and they can work independently. You can update one of them without having to worry about changes in others. This makes it very loosely coupled and at the same time available for working together by merging with other components to bring out the best of the web application’s abilities. This is not something unique in React library. In fact, components are the basic building blocks in the Angular framework as well, and a similar concept has been there in many MVC frameworks since a long time. 2. High PerformanceWith component-based architecture, React allows to create highly scaled Single Page Application or SPA, in which content is dynamically loaded during user interaction without loading the entire page. However, this can turn into a trap. Imagine having to update DOM for every change caused by user’s interaction on web page. Every action might force DOM (which is a tree structure) to refresh itself. And if your web page is complex, having multiple UI components this can cause massive performance blockage. To solve this, React uses the concept of Virtual DOM, which you can think of as a copy of your real DOM. Now all the changes caused by user’s interaction or other events are handled by the virtual DOM first, and only if it (the intelligence of React) thinks it is important enough to refresh the real DOM, the real DOM is refreshed. This saves us from massively repeating recreation of the DOM tree for every trivial change resulting in high performance application.3. ReduxBack to our SPA (Single Page Application), where there are multiple components sitting on one page and updated dynamically without reloading the entire page. Now all this sounds very simple and smooth. Which it is, until your components start talking to each other. Let’s say you have a web page where there are few form components which contains large forms with lot of controls, few table components, and a sidebar and header, footer. Content in tables must be updated when user submits form or part of forms. Also, you might want to update header when a new record is created. Now here, our table components have dependency on form components. These dependencies, along with communication between them can grow as your application grows. All this can make our data unstable as there is no way to know which data is latest or which is correct. There is no single source of data. This can cause poor user experience and also performance issues. To make sure that all your components are in sync with latest data, we need to have a--let’s just call it-- a ‘manager’ who manages our data, and provides a single trustworthy source which makes sure the data which the components have is correct and truthful. This manager and its team are known as Redux in React.  Redux forces components to avoid talking to each other directly or being dependent on each other, instead components send their data to redux and it is the responsibility of redux to update the components (which need those data) with new data. This way components are always updated with the latest data available without having to depend on each other.4. Easy to LearnThis is another pro of working with React as any developer with understanding of html and JavaScript can start learning React. Unlike other JS frameworks like Angular which introduce a lot of new terminologies, React uses most of what is already available. This makes it very easy to start with--another reason why it has grown to be the most popular JS library.  It provides more flexibility (which it derives from Vanilla JavaScript) and does not force developers to follow any specific pattern like MVC or any other architectural pattern. Development teams are free to choose their own style or patterns while working with an application. This allows vanilla JavaScript developers to work with component-based architecture without having to lose the freedom they enjoyed with vanilla JavaScript. 5. Mobile App DevelopmentIn a world where every platform, and every stack of an application requires you to learn a whole new tool or language or frameworks; React brings us the flexibility of using the same library over web and mobile applications. React Native allows us to create mobile applications on any mobile platform with the same React concepts and syntaxes. React Native helps you create interactive and high-performance mobile apps for any mobile device without having to learn a new tool or language. So far, we talked about what makes React so popular among development teams, but every technology has pros and cons. Let’s talk about why many teams are not willing to work with React and what makes it less reliable when you need a well-structured and stable JS library to work with. Cons  1. High Pace of DevelopmentThis is arguably the most discussed con of using React. React is not just a rapidly growing library, it is also rapidly changing, which forces its developers to update the way they write code. Now this is obviously annoying for most of the developers who are not comfortable with adopting new ways every Monday they start or the ones who are working on an application where changes are critical to customers. There are many industries which are critical to change where customers look for more stable tools and technologies. But this again depends on how expert team members are and if they can convince their customers to trust them with React.  2. Flexibility and Lack of ConventionsYes, you read it right. I know that we discussed it as an advantage of using React, but at the same time it is also a disadvantage in a broader sense. Libraries, languages, or frameworks have their global standards of how developers work with them, and what styles or patterns they follow. This is useful because when developers change teams, they have an idea of what patterns or styles the new team might be following; whereas among React development teams it is not easy to predict what styles or standards a team might follow, making it harder for new developers to work with new teams and their standards. Developers who have worked with frameworks which follow a fixed structure and set of conventions might not find React very attractive to work with. 3. Not a full-featured frameworkEven though React is a rich JavaScript library with a set of interactive and useful features required for creating large scale applications, developers do not enjoy what they can have in a fully featured framework such as Angular (another popular JS Framework). If you look at the MVC (Model View Controller) architecture, React only handles the view part. For Controller and Model you need additional libraries, and tools. This can result in poor structure of code, and its patterns. Whereas frameworks like Angular provide the complete MVC featured ground, which is more structured, and well managed.  This all sounds like jQuery again. When we talk about empowering JavaScript to structure like we do our code at backend, arguably you might be looking for a full featured, well-structured tool where similar practices and patterns are followed globally, and this is where React might not be very helpful. If not careful, you might end up having the same problem which React claims to resolve. It needs a quite deeper understanding of JavaScript and its core behaviors to make React work the way you want it to. Whereas working with Frameworks like Angular (although it is more difficult to learn than React) force developers to follow a strict structure where you enjoy similar patterns as backend development.4. Poor DocumentationSince React is changing so fast, new tools and patterns are adding up every now and then, and it is becoming difficult for the community to maintain the documentation. This makes it difficult to work with for new developers who want to start with React. Lack of poor documentation can also result in slower development among teams with less experienced developers. 5. JSXReact has introduced JSX to work with html, and JavaScript. This is like JavaScript and html syntax, and allows to mix html and JavaScript together but has some new attributes and syntaxes, which makes it difficult to work with when you start with React. For example, while working with class attribute, in JSX it becomes className. Also, the lack of rich documentation makes it more difficult to work with JSX.  This is what a JSX looks like while creating a simple login form.      Header {this.state.content}      Enter your username:          Enter your password:            6. SEO HandlingIf you are building an application in React which is SEO (Search Engine Optimization) sensitive where the popularity of your application, its appearance and ranking in Google search results are priorities, then this, although not proven, is a concern. The concern is about ability of search engine crawlers to list dynamically loaded content. There are tools available to test your app for SEO results and rankings.Pros from Developer’s Perspective Easy to Learn: The biggest advantage that React has from the developer’s perspective, which is also the reason behind React getting more popular than other JavaScript libraries and frameworks, is that it is very easy to begin with. Anyone with basic understanding of HTML and JavaScript can quickly get started with React. Even though it has JSX to mix JavaScript and HTML together which is bit unconventional, it hasn’t stopped React from becoming the most loved JavaScript library among developers.  Structural Flexibility Unlike other conventional frameworks, React doesn’t draw boundaries on how a developer should treat code. This gives React developers freedom to express their own architectural styles to build apps. Developers who like to work with vanilla JavaScript love this flexibility as they are not used to the idea of a framework controlling the structure of code in an application. Pros from Business Owner’s Perspective One framework for all Platforms Most of the technology stacks force the use of different tools, language or frameworks for web and mobile app development. This requires business owners to hire developers of different skill sets for web and mobile app development, increasing the cost of app development and maintenance in the long run. With React, the easier learning curve allows a React web developer to quickly start with React Native, which is a mobile development framework based on React. This reduces the cost of hiring developers of multiple skill sets and also reduces the cost of maintenance, as the same technology is being used at both the platforms. Rapid Development Time is another significant factor when it comes to software development, as it directly impacts the cost of project development. React is easy to get started with, and has the structural flexibility that allows developers to do rapid application development, reducing both the time and cost of software development. This not only applies to web but mobile development as well. There are many businesses who had to choose between web and mobile apps while in their initial phases because of time and cost constraints. React has been able to give the confidence to start with mobile and web app development simultaneously, allowing them to reach a lot more customers than they would have had if they had to choose between web and mobile. Conclusion Honestly, there is no solid conclusion on whether these pros or cons can be summed up to decide if you should or should not go with React. It entirely depends on customer needs, domain needs and expertise in your team. With the right team of experts React can be implemented at its best, overcoming its cons like “rapid change or lack of documentation and lack of convention”. A team of expert developers can agree to follow a convention, document the practices and patterns they are following for any future developers who might join their team. With all these covered, React has a number of advantages including “Hight performance using Virtual DOM, State Management using Redux”, which you can use to make the best of web and mobile apps available today.
5816
What are the Pros and Cons of React

If you are a web developer, you are a JavaScript... Read More

What is query string in Node.js?

In this article, we will look into query string module in Node.js, and understand a few methods to deal with query string. The available methods can be used to convert query string into a JSON object and convert a JSON object into query string.What is Query StringA query string according to Wikipedia is a part of the uniform resource locator (URL), that assigns values to specified parameters. In plain English it is the string after the ? in a url. Some url examples are shown below.https://example.com/over/there?name=ferret https://example.com/path/to/page?name=ferret&color=purpleThe query string in first case is name=ferret and in second case is name=ferret&color=purpleNode.js Query string moduleNow, the Node.js query string module provides methods for parsing and formatting URL query strings. The query string module can be accessed using the below –const querystring = require(‘querystring’)We will now look into the below six methods in the next section.querystring.decode()querystring.encode()querystring.escape(str)querystring.parse(str[, sep[, eq[, options]]])querystring.stringify(obj[, sep[, eq[, options]]])querystring.unescape(str)Query String methods with descriptionLet us look into a real example to understand the important Query string methods. Let us setup a basic Node application by giving the command npm init -y in terminal, inside a folder. I had created an empty NodeJS folder for the same.$ npm init -y Wrote to D:\NodeJS\package.json: {   "name": "NodeJS",   "version": "1.0.0",   "description": "",   "main": "index.js",   "scripts": {     "test": "echo \"Error: no test specified\" && exit 1"   },   "keywords": [],   "author": "",   "license": "ISC" }The above commands create a basic package.json file, which is the basis of any Node.js project. We are using the -y option, so that we don’t have to enter the details manually.Next, open the folder in a code editor which is VSCode in my case. Here, I have created a file querystring.js and the first line contains the importing of querystring module.querystring.parse() MethodThe querystring.parse() method is used to parse the URL query string into an object that contains the key value pair. The object which we get is not a JavaScript object, so we cannot use Object methods like obj.toString, or obj.hasOwnProperty().The latest UTF-8 encoding format is assumed unless we specify a different encoding format. But we should stick to UTF-8 encoding as it is the standard and contains all international characters like the Chinese characters and the hindi characters. After that also if we need alternative character encoding, then the decodeURIComponent option should be used.The syntax for the method is below.querystring.parse( str[, sep[, eq[, options]]]) )As seen from the above syntax the method accepts four parameters, and they are described below.str: This is the only required string field and it specifies the query string that has to be parsed.sep: It is an optional string field, which if given specifies the substring used to delimit the key and value pairs in the query string. The default value which is generally used is “&”.eq: It is an optional string field that specifies the substring used to delimit keys and values in the query string. The default value which is generally used is “=”.options: It is an optional object field which is used to modify the behaviour of the method. It can have the following parameters:decodeURIComponent: It is a function that would be used to specify the encoding format in the query string. The default value is querystring.unescape(), about which we will learn later.maxKeys: It is the number which specifies the maximum number of keys that should be parsed. A value of “0” would remove all the counting limits, and it can parse any number of keys. The default value is set at “1000”.The below example shows the various options used in querystring.parse() method. Add the below code in querystring.js file, which we created earlier.// Import the querystring module const querystring = require("querystring");   // Specify the URL query string to be parsed   let urlQueryString = "name=nabendu&units=kgs&units=pounds&login=false";   // Use the parse() method on the string   let parsedObj = querystring.parse(urlQueryString);   console.log("Parsed Query 1:", parsedObj);   // Use the parse() method on the string with sep as `&&` and eq as `-` urlQueryString = "name-nabendu&&units-kgs&&units-pounds&&login-true"; parsedObj = querystring.parse(urlQueryString, "&&", "-");   console.log("\nParsed Query 2:", parsedObj); // Specify a new URL query string to be parsed   urlQueryString = "type=admin&articles=java&articles=javascript&articles=kotlin&access=true"; // Use the parse() method on the string with maxKeys set to 1   parsedObj = querystring.parse(urlQueryString, "&", "=", { maxKeys: 1 });   console.log("\nParsed Query 3:", parsedObj);   // Use the parse() method on the string with maxKeys set to 2   parsedObj =  querystring.parse(urlQueryString, "&", "=", { maxKeys: 2 });   console.log("\nParsed Query 4:", parsedObj); // Use the parse() method on the string with maxKeys set to 0 (no limits) parsedObj = querystring.parse(urlQueryString, "&", "=", { maxKeys: 0 }); console.log("\nParsed Query 5:", parsedObj);Now, run the command node querystring.js from the Integrated terminal in VSCode or any terminal. Note that you need to be inside the folder NodeJS, which we had created earlier. The output of the same will be below.Parsed Query 1: [Object: null prototype] { name: 'nabendu', units: [ 'kgs', 'pounds' ], login: 'false' } Parsed Query 2: [Object: null prototype] { name: 'nabendu', units: [ 'kgs', 'pounds' ], login: 'true' } Parsed Query 3: [Object: null prototype] { type: 'admin' } Parsed Query 4: [Object: null prototype] { type: 'admin', articles: 'java' } Parsed Query 5: [Object: null prototype] {   type: 'admin',   articles: [ 'java', 'javascript', 'kotlin' ],   access: 'true' }querystring.stringify() MethodThe querystring.stringify() method is used to produce a query string from a given object, which contains a key value pair. It is exactly the opposite of querystring.parse() Method.It can be used to convert the string, numbers and Boolean values for the key. You can also use an array of string, numbers or Boolean as values. This method of changing an object to query string is called serialized.The latest UTF-8 encoding format is assumed unless we specify a different encoding format. But we should stick to UTF-8 encoding as it is the standard and contains all international characters like the Chinese characters and the Hindi characters. If we still need an alternative character encoding, then the decodeURIComponent option should be used.Syntax for the method is below.querystring. stringify( obj[, sep[, eq[, options]]]) )As from the above syntax the method accepts four parameters, and they are described below.obj: This is the only required object field and it specifies the object that has to be serialized.sep: It is an optional string field, which if given specifies the substring used to delimit the key and value pairs in the query string. The default value which is generally used is “&”.eq: It is an optional string field that specifies the substring used to delimit keys and values in the query string. The default value which is generally used is “=”.options: It is an optional object field which is used to modify the behaviour of the method. It can have the following parameters:decodeURIComponent: It is a function that would be used to specify the encoding format in the query string. The default value is querystring.escape(), about which we will learn later.The below example shows the various options used in querystring.stringify() method. Add the below code in querystring.js file, which we created earlier.// Import the querystring module   const querystring = require("querystring");   // Specify the object that needed to be serialized   let obj = {   name: "nabendu",   access: true,   role: ["developer", "architect", "manager"],   };   // Use the stringify() method on the object   let queryString = querystring.stringify(obj);   console.log("Query String 1:", queryString);   obj = {       name: "Parag",       access: false,       role: ["editor", "HR"],   };   // Use the stringify() method on the object with sep as `, ` and eq as `:` queryString = querystring.stringify(obj, ", ", ":");   console.log("Query String 2:", queryString);   // Use the stringify() method on the object with sep as `&&&` and eq as `==`   queryString = querystring.stringify(obj, "&&&", "==");   console.log("\nQuery String 3:", queryString);Now, run the command node querystring.js from the Integrated terminal in VSCode or any terminal. Note that you need to be inside the folder NodeJS, which we had created earlier. The output of the same will be below.Query String 1: name=nabendu&access=true&role=developer&role=architect&role=managerQuery String 2: name:Parag, access:false, role:editor, role:HR        Query String 3: name==Parag&&&access==false&&&role==editor&&&role==HRquerystring.decode() MethodThe querystring.decode() method is nothing but an alias for querystring.parse() method. In our parse example, we can use it. So, add the below code in querystring.js file, which we created earlier.// Import the querystring module const querystring = require("querystring");   // Specify the URL query string to be parsed   let urlQueryString = "name=nabendu&units=kgs&units=pounds&login=false";   // Use the parse() method on the string   let parsedObj = querystring.decode(urlQueryString); console.log("Parsed Query 1:", parsedObj);As earlier, run the command node querystring.js from a terminal. And the output will be same as that with querystring.parse() method.Parsed Query 1: [Object: null prototype] { name: 'nabendu', units: [ 'kgs', 'pounds' ], login: 'false' }querystring.encode() MethodThe querystring.encode() method is nothing but an alias for querystring.stringify() method. In our stringify example, we can use it. So, add the below code in querystring.js file, which we created earlier.// Import the querystring module   const querystring = require("querystring");   // Specify the object that needed to be serialized let obj = { name: "nabendu", access: true,   role: ["developer", "architect", "manager"],   };   // Use the stringify() method on the object   let queryString = querystring.encode(obj);   console.log("Query String 1:", queryString);As earlier run the command node querystring.js from a terminal. And the output will be same as that with querystring.stringify() method.Query String 1: name=nabendu&access=true&role=developer&role=architect&role=managerquerystring.escape(str) MethodThe querystring.escape() method is used by querystring.stringify() method and is generally not used directly.querystring.unescape(str) MethodThe querystring.unescape() method is used by querystring.parse() method and is generally not used directly. SummaryIn this article we learnt about the useful query string module in Node.js, which is mainly used to parse URL query strings into Object format and also to change an object to URL query strings.
3465
What is query string in Node.js?

In this article, we will look into query string mo... Read More