Search

Instal React Js on Windows

IntroductionIn 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.  Atom https://atom.io/Sublime https://www.sublimetext.com/Visual studio code https://code.visualstudio.com/download.2. 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 URL https://nodejs.orgDepending 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

Introduction

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 https://nodejs.org

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.

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 button

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.

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 prompt

Press keys Win+R

And type cmd in the window below.

Next Click on Ok or Press Enter on the keyboard.

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

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.

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 react


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

Behind 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-app

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

Next, type the following command mkdir react-cliNow 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


When 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 below

cd my-fast-app

And enter the next command as npm start

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.

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.

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.

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

Make API Calls the Right Way in Angular

About Angular 10Angular 10 is the latest version of the Angular family. Angular applications are basically designed for Single Page Applications, where all controls are required in single page architecture. Angular is an application based design framework, which provides the Cross-Platform development environment for creating the most sophisticated SPAs. These SPAs are efficient enough for giving us a component to view to model environment, making it an MVC or MVVM application.Angular provides a Progressive Web App architecture, which means that an application made in Angular gives us an App like experience with high performance. Angular has zero-step installation, making its up- gradation using modern web capabilities possible, even if offline. Angular has the capability of making cross platform Desktop Apps which can be created using MAC, Windows, or Linux OS using the same Angular methods. Angular can be rendered in Node.js, Microsoft .Net, PHP and many other servers by giving the output in HTML-CSS format. This even optimizes the app for SEO. Angular framework turns our templates into JavaScript Virtual machine codes which are highly optimized. With Angular CLI, the Command Line tools, we can build and deploy Apps faster than ever before. Angular uses Karma for unit tests and Protractor for scenario tests making the applications made in Angular more stable.IntroductionFront-end applications in today’s programming world use HTTP protocol modules to talk to the back-end services. Almost all current browsers make this communication via two ways, one by HTTPrequests through XMLHttpRequest interface and the other by the API fetch() method call.We usually make API calls to remote HTTP servers via HttpClient module of Angular 10 by sending HTTP requests. HttpClient has methods which perform HTTP requests. HttpClient is an injectable class for Angular 10. The methods of this class have request methods with many types of signatures, and their return types are different based on the signature of the request, thus giving different response types.We will study about HttpClient in detail in the subsequent passage.The Common MistakeOne thing for sure is that we need to call APIs in our programs. If we do so correctly, it can help us in upgrading to further versions, in making test modules, and even in handling errors. One common mistake that programmers usually make is in the call they use API URLs directly in the component. This means that if the API URL is upgraded for any reason, we will need to upgrade the URLs in every single component. For Eg: this.httpClient.get('https://www.userdomain.com/api_name/data/' + this.id);  Again, since we are not validating the path by using the Path variable of Angular, this call might fail if the URL is not valid or not available for some reason. Also, changing the modules with direct call to httpClient will require a lot of changes in the component. Let us now talk about the right approach.The Right WayThe correct approach towards calling APIs in Angular includes the following:Create ConstantsWe need to set global variables in Angular 10 to access our variables synchronously throughout our application. We declare Global variables in a Global Constant file. Create a folder under src/app and name it config. To create the global constant file, name it constants.ts and place it under src/app/config folder.Eg: create the following file: src/app/config/constants.ts Open this file and put global constants like API_ENDPOINT, API_MOCK_ENDPOINT etc. These global variables will be used later in Component files like AppComponent so that they can be used like Site constants. Declaring Global Constants // Angular Modules import { Injectable } from '@angular/core';  @Injectable()  export class Constants { public readonly API_ENDPOINT: string = ' https://www.userdomain.com/';  public readonly API_MOCK_ENDPOINT: string = 'https://www.userdomainmock.com/';  public static TitleOfSite: string = " Making API calls the Right Way by Monica";  }  An example of AppComponent using the above global constant is:  Edit the app.component.ts file from the src/app folder:  src/app/app.component.ts:  import { Component, OnInit } from '@angular/core'; import{ Constants } from './config/constants';  @Component({    selector: 'app-root',    templateUrl: './app.component.html',    styleUrls: ['./app.component.css']  })  export class AppComponent implements OnInit{      title = Constants.TitleOfSite;      constructor() {          console.log(GlobalConstants.API_ENDPOINT);      }      ngOnInit() {          console.log(this.title);      }  } Run the project by navigating to the project folder and calling ng serve : $ cd hello-world  $ ng serve  The output will be seen in the browser: https://www.userdomain.com/ Making API calls the Right Way by MonicaCreate a ServiceTo create a service in Angular 10, create a file api-http.service.ts in the src/app/core/services folder. Add the following code in the file as below: // Angular Modules import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Injectable() export class ApiHttpService { constructor( // Angular Modules private http: HttpClient ) { } public get(url: string, options?: any) { return this.http.get(url, options); } public post(url: string, data: any, options?: any) { return this.http.post(url, data, options); } public put(url: string, data: any, options?: any) { return this.http.put(url, data, options); } public delete(url: string, options?: any) { return this.http.delete(url, options); } }Use HTTPClient LibraryHttpClient Library is present in @angular/common/http folder. The older version of HttpClient was in @angular/http folder, this is replaced by the upgraded version of the same in @angular/common/http folder.Almost all current browsers communicate with APIs via two ways, one by HTTPrequests through XMLHttpRequest interface and the other by the API fetch() method call.The HttpClient module is built over XMLHttpRequest interface. It wraps all the complexities of this interface and provides extra features like: RxJS Obervables, Interceptors for requests and responses, Typed requests and responses, Error handling techniques, ease in Testing Modules, etc. Benefits of using HTTPClient LibraryHttpClient is a module found in angular/common/http module. HttpClient is based on XMLHttpRequest interface, the Interface which is commonly given by most modern browsers. HttpClient gives us a lot more than XMLHttpRequest, and some of its benefits are:It gives us ease in using testing modules.It has request and response objects in strongly typed manner.It has APIs Support with Observable class object.It provides error handling modules.Importing the libraryIn order to use HttpClient library we need to import HttpClientModule from the @angular/common/http package and include the library in the imports array of the App module : Edit the AppModule file in the src/app folder and add the line on top of the file as follows: src/app/app.module.ts: import { HttpClientModule } from '@angular/common/http'; Configure HTTPClientIncluding HttpClient: Once done, include HttpClientModule in the imports array of the app.module and further use it:import { NgModule }         from '@angular/core'; import { BrowserModule }    from '@angular/platform-browser'; import { HttpClientModule } from '@angular/common/http'; @NgModule({   imports: [     BrowserModule,     // import HttpClientModule after BrowserModule.     HttpClientModule,   ],   declarations: [     AppComponent,   ],   bootstrap: [ AppComponent ] }) export class AppModule {} …Now we are ready to use the HttpClient library to send HTTP requests or receive API response. Injecting HttpClient into our Application: Once we have  imported HttpClientModule into the AppModule, we can inject the HttpClient into our application as:import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Injectable() export class ConfigService {   constructor(private http: HttpClient) { } }Create a query parameterGetting JSON dataIn this example we will request JSON data from the API server. Here our app needs a configuration file on the server, config.json, that specifies resource URLs.{   "demoUrl": "api/demo",   "filename": "assets/demotextfile.txt" } The ConfigService fetches this file with a get() method from HttpClient library as follows: configUrl = 'assets/config.json'; getConfig() {   return this.http.get(this.configUrl); }A component, such as ConfigComponent, injects the ConfigService and this getConfig service method is called from the component as for example:showConfig() {   this.configService.getConfig()     .subscribe((data: Config) => this.config = {         demoUrl: data['demoUrl'],         filename:  data['filename']     }); }The service method returns an Observable object of configuration data. Thus the component subscribes to the method's return value. The subscription callback copies the data fields into the component's config object, which binds the data in the component template for display.We can get the Observable object of typed HTtpResponse from the HttpClient as follows:getConfigResponse(): Observable {   return this.http.get(     this.configUrl, { observe: 'response' }); }Here, HttpClient.get() returns an Observable object of typed HttpResponse rather than just the JSON data.The showConfigResponse() method of the component displays the response headers as well as the configuration.Create Error HandlerHttpClient returns an error object instead of a successful response if a request fails on the server. This usually happens due to a request fail, poor network connection or other network related issues.We can create an error handler component by adding a second callback to the.subscribe():showConfig() {   this.configService.getConfig()     .subscribe(       (data: Config) => this.config = { ...data }, // success path       error => this.error = error // error path     ); }We can give different reasons and feedback for a failed request, but displaying the error object can also help at times. @angular/common/http@angular/common/http implements an HTTP client API for Angular apps that relies on the XMLHttpRequest interface exposed by browsers.This includes testability features, typed request and response objects, request and response interception, observable APIs, and streamlined error handling.Entry point exportsNgModulesHttpClientJsonpModuleConfigures the dependency injector for HttpClient with supporting services for JSONP. Without this module, Jsonp requests reach the backend with method JSONP, where they are rejected.HttpClientModuleConfigures the dependency injector for HttpClient with supporting services for XSRF. Automatically imported by HttpClientModule.HttpClientXsrfModuleConfigures XSRF protection support for outgoing requests.ClassesHttpBackendA final HttpHandler which will dispatch the request via browser HTTP APIs to a backend.HttpClientPerforms HTTP requests. This service is available as an injectable class, with methods to perform HTTP requests. Each request method has multiple signatures, and the return type varies based on the signature that is called (mainly the values of observe and responseType).HttpErrorResponseA response that represents an error or failure, either from a non-successful HTTP status, an error while executing the request, or some other failure which occurred during the parsing of the response.HttpHandlerTransforms an HttpRequest into a stream of HttpEvents, one of which will likely be a HttpResponse.HttpHeaderResponseA partial HTTP response which only includes the status and header data, but no response body.HttpHeadersRepresents the header configuration options for an HTTP request. Instances are immutable. Modifying methods return a cloned instance with the change. The original object is never changed.HttpParamsAn HTTP request/response body that represents serialized parameters, per the MIME type application/x-www-form-urlencoded.HttpRequestAn outgoing HTTP request with an optional typed body.HttpResponseA full HTTP response, including a typed response body (which may be null if one was not returned).HttpResponseBaseBase class for both HttpResponse and HttpHeaderResponse.HttpUrlEncodingCodecProvides encoding and decoding of URL parameter and query-string values.HttpXhrBackendUses XMLHttpRequest to send requests to a backend server.HttpXsrfTokenExtractorRetrieves the current XSRF token to use with the next outgoing request.JsonpClientBackendProcesses an HttpRequest with the JSONP method, by performing JSONP style requests.JsonpInterceptorIdentifies requests with the method JSONP and shifts them to the JsonpClientBackend.XhrFactoryA wrapper around the XMLHttpRequest constructor.StructuresHttpDownloadProgressEventA download progress event.HttpEventTypeType enumeration for the different kinds of HttpEvent.HttpInterceptorIntercepts and handles an HttpRequest or HttpResponse.HttpParameterCodecA codec for encoding and decoding parameters in URLs.HttpProgressEventBase interface for progress events.HttpSentEventAn event indicating that the request was sent to the server. Useful when a request may be retried multiple times, to distinguish between retries on the final event stream.HttpUploadProgressEventAn upload progress event.HttpUserEventA user-defined event.TypesHTTP_INTERCEPTORSA multi-provider token that represents the array of registered HttpInterceptor objects.HttpEventUnion type for all possible events on the response stream.HttpClient vs HttpBackendHttpBackendA final HttpHandler which will dispatch the request via browser HTTP APIs to a backend.Interceptors sit between the HttpClient interface and the HttpBackend.When injected, HttpBackend dispatches requests directly to the backend, without going through the interceptor chain.abstract class HttpBackend implements HttpHandler {   abstract handle(req: HttpRequest): Observable }HttpClientPerforms HTTP requests. This service is available as an injectable class, with methods to perform HTTP requests. Each request method has multiple signatures, and the return type varies based on the signature that is called (mainly the values of observe and responseType).Note that the responseType options value is a String that identifies the single data type of the response. A single overload version of the method handles each response type. The value of responseType cannot be a union, as the combined signature could imply.class HttpClient { request(first: string | HttpRequest, url?: string, options: { body?: any; headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: HttpObserve; params?: HttpParams | { [param: string]: string | string[]; }; reportProgress?: boolean; responseType?: "arraybuffer" | ... 2 more ... | "json"; withCredentials?: boolean; } = {}): Observable   delete(url: string, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: HttpObserve; params?: HttpParams | { [param: string]: string | string[]; }; reportProgress?: boolean; responseType?: "arraybuffer" | ... 2 more ... | "json"; withCredentials?: boolean; } = {}): Observable   get(url: string, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: HttpObserve; params?: HttpParams | { [param: string]: string | string[]; }; reportProgress?: boolean; responseType?: "arraybuffer" | ... 2 more ... | "json"; withCredentials?: boolean; } = {}): Observable   head(url: string, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: HttpObserve; params?: HttpParams | { [param: string]: string | string[]; }; reportProgress?: boolean; responseType?: "arraybuffer" | ... 2 more ... | "json"; withCredentials?: boolean; } = {}): Observable   jsonp(url: string, callbackParam: string): Observable   options(url: string, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: HttpObserve; params?: HttpParams | { [param: string]: string | string[]; }; reportProgress?: boolean; responseType?: "arraybuffer" | ... 2 more ... | "json"; withCredentials?: boolean; } = {}): Observable   patch(url: string, body: any, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: HttpObserve; params?: HttpParams | { [param: string]: string | string[]; }; reportProgress?: boolean; responseType?: "arraybuffer" | ... 2 more ... | "json"; withCredentials?: boolean; } = {}): Observable   post(url: string, body: any, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: HttpObserve; params?: HttpParams | { [param: string]: string | string[]; }; reportProgress?: boolean; responseType?: "arraybuffer" | ... 2 more ... | "json"; withCredentials?: boolean; } = {}): Observable   put(url: string, body: any, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: HttpObserve; params?: HttpParams | { [param: string]: string | string[]; }; reportProgress?: boolean; responseType?: "arraybuffer" | ... 2 more ... | "json"; withCredentials?: boolean; } = {}): Observable }The request that we send by HttpClient always go through interceptor of Angular application and the request we send by HttpBackend will dispatch requests directly to the backend, without going through the interceptor chain. So we should use both HttpClient and HttpBackend to send a request.Citation: https://angular.io/api/common/httpConclusionThe above article included all the information that we need for working with APIs for Angular Applications. We worked with the Http module and HttpClient Module. We worked with services and efficient API Calls. We understood how to improve on calling API from an Angular Application.
3393
Make API Calls the Right Way in Angular

About Angular 10Angular 10 is the latest version o... Read More

Installation of React on Mac

Hello learners! In this tutorial we are going to learn the installation of React.js library on macOS. React.js is a library which helps developers to develop highly efficient data-driven SPA apps. It is based on functional programming, relies on the concept of immutability and encourages component-based architecture based on Single reusability principle.Before we perform the installation steps, we need to look at the prerequisites needed for installation.1. PrerequisiteSystem requirements: mac OS > 10.10Minimum RAM: 4 GBStorage space: 10 GB available spaceInternet browser: Chrome, Safari, Opera, Microsoft EdgeInternet connectivity: 512 kbps and above2. Introduction to ReactIn this tutorial, we will install the react library on macOS. Before the installation, we need to have a quick understanding of React.React is a library which helps web developers and architects to serve the needs of customers having demands of high data flow and fast responsive UIs in the context of data.It is based on the components-based architecture. The webpage can be represented in the form of Parent and Child based components.  It relies heavily on Virtual DOM, which acts as a performance optimization to DOM operations.A Web page which is composed of HTML has a DOM tree, with the help of which the web page is rendered by the browser.When the user is interacting on a page, it involves addition and insertion of information based on the user activity.  for e.g. A user has added an item to the cart. The cart is showing the updated item to reflect the user’s decision.Behind the scene, the HTML document undergoes a certain transform which helps to share the updated page. As we have mentioned, the HTML document is represented by the DOM tree. In the above scenario, the DOM needs some changes which involve addition and deletion of certain HTML nodes. This helps to show the relevant information which represents what a user is trying to achieve in the context of updating his buying choice.For this insertion and deletion operation on HTML DOM, there is a memory cost involved.Virtual DOM acts as a performance optimizer as far as the DOM update operations are concerned.  It maintains two copies; one is the real copy of the DOM (react DOM) and another one is the change to be done. The process by which minimal change takes place on the react DOM is also studied under the process called reconciliation.To understand the DOM we can visualise it as a tree.  The tree has roots and branches. In a similar manner the DOM has the HTML element at the top and down below there are nodes which are connected to the parent node. In terms of tree analogy, we can represent the parent node as the trunk, with various nodes connected to the trunk. And on these nodes, the insertion and deletion operations get optimized by using React.3. A short intro to Node.js & npmRyan Dahl is the inventor of Node.js.Node.js code is an open source, cross-platform, JavaScript runtime environment that runs JavaScript code. It is based on the Chrome V8 engine. Chrome V8 engine is written in C++. It runs on Windows, macOS and Linux.After installation of Node.js, we can run the react based project locally on our system during development. This also allows us to deploy our app on the production server.Some of the features of Node.js include:a. Uses JavaScript as primary languageb. Non-blocking I/Oc. Supports Asynchronous programmingd. Can handle multiple connections requests by using a single serverNode.js allows us to perform read, write operations on the server.It also provides the functionality to work with the databases.Npmjs.org is an online code repository of thousand modules (npm) and it allows us to install node modules using basic commands. Some modules are independent and some are interrelated to run effectively, due to dependencies between them.Node.js hosts several modules and instead of building functionality from scratch, it is easier for us to look for a module and reuse and extend its functionality. Developer projects generally have time and budget constraints. For the developer community, npmjs.org acts as a lifesaver as far as the Node.js based development is concerned.4. Download Node.js and installationTo install Node.js there are various steps.  It can be installed by visiting https://nodejs.org/en/download/Once we have downloaded the Node.js version based on the operating system, we can perform the installation steps.One thing we need to note is that NPM is auto-installed with Node.js installation.We need to click on the package file which we have downloaded node-v14.15.1.pkgIn the below installation we can see it will install Node.js  v14.15.1 and npm v6.14.8When we click on the Continue button, the installer will ask to ‘Read Licence’.  It also shows two-buttons-- Disagree and Agree.To install the Node.js we need to click on Agree.To proceed further we need to specify the Login password to continue the installation.In the below screenshot the user has administrative rights for software installation. So, the admin needs to type the password in order to proceed further.After clicking on the Install Software button, click on the Install button.In the next screen, the progress bar will indicate the installation progress.Post-installation, it will provide us with a summary as below.After closing this window by clicking on the close button, we need to verify whether we have installed the said version of Node.jsTo open command terminal, press Command + Space barThis will open Spotlight search as below.We need to type Terminal and hit enter.Once the terminal is visible, we need to type the following commandnode - vAs we can see it is showing us the node version (v14.15.1) as in the screenshot.So, we have installed Node version 14. Each build is denoted by semantic versioning. The first digit, in this case, is 14, which represents a major release. The second digit represents new features with the release and the third digit represents patch and bug fixes as associated with the major release.Node.js installation by command line.As an alternative method, we can install node.js by the terminal as well. But as a prerequisite, we need to have homebrew (https://docs.brew.sh/Installation)  in MacOS.We are assuming, we have homebrew installed in our system.And to proceed with the command-line installation, we need to open the terminal and type the following command.brew - vThe above command will inform us about the homebrew version.To update the brew, type the following commandbrew updateAfter the above command has been executed, we need to typebrew install nodeThe installation will take some time, so give some time to the system and be patient.To verify the Node.js installation usenode -vTo verify the npm installation usenpm -vCongratulations, we have installed Node.js and NPM.5. Create-react-app for react app on macOSNow, we are going to install create-react-app on macOS.Create-react-app is a quick way to set up a single page application code with minimal steps and no configuration.Let’s proceed with the installation steps.Please type the following command in the terminal to create a folder with the name react-app. mkdir react-appThen navigate to directory react-app as follows:cd react-appTo verify directory, type command and enter as belowpwdOnce we have confirmed that we are in the right directory type below command.npx create-react-app my-appnpx is a module which is included with npm.The installation steps as shown in the above screenshot will take some time.So, sit back and relax.Once the above command has been executed successfully....….navigate to my-app directorycd  my-appAnd typenpm startWhen the command is executed successfully, it will open the browser at localhost:3000 in the browser.And we can give ourselves a pat on back for the small win!6. Download and Install React (Explicit command)This step is for awareness only.In the previous step, we have not explicitly installed React.js as this is installed with the help of create-react-app package.We can also install the React.js  by using the following command.  And we may need to install the module dependencies on our own.npm install react --save7. File folder and structureWe can see that we have not touched the codebase but found the minimal single page web application running on our macOS.To see the code structure, we need to open the code editor e.g. Sublime, Atom etc.And open the folder my-appAs we can see, there are various folders and at a high level there are below folders:node_modules public srcIn the public folder, we can see index.html. This is the page template.The index.js in src folder is the JavaScript entry point.The app is displaying the code from the App.js in the src folder.In the my-app folder, the package.json is an important file which mentions the app name and module dependencies. Feel free to explore further.8. Summary (conclusion)In this tutorial, we have learnt about React.js, and the component-based architecture model in React.js. We also had a high-level overview of the virtual DOM.We touched on the concept of reconciliation, the usage of Node.js in the world of JavaScript and its capability to handle non-blocking I/O output to fulfil client connection requests simultaneously.We have checked two methods for Node.js installation, namely with the package manager and another one by using the command line.To install React.js, we have relied on the create-react-app module for a quick start. We can also install the React.js by command line. To prevent being overwhelmed with too many details we have picked the create-react-app method for this tutorial. We created our first react app and saw it running.To become familiar with the code in terms of development perspective, we quickly checked the important files which are running the app.
3496
Installation of React on Mac

Hello learners! In this tutorial we are going to l... Read More

How to add React to an existing website?

React, originally created by Facebook, is a popular user interface JavaScript framework which is used for creating front-end applications. It is one of the most popular frameworks used by developers to create fast scalable applications using a declarative approach that ties up JavaScript with an HTML-like syntax known as JSX. Building up or setting up React applications requires many dependencies, such as using a compiler or setting up the node and versioning etc.In order to get rid of the above complications and set up SPAs (Single Page applications) in simple steps, a CLI tool named create-react-app was made.  In this article we will learn how to set up your React app in no time, with an easier approach and without getting into any complications. And what’s more, here, we will not need to configure or install any tools like webpack or Babel.   Create-React-APP will take care of such things with its preconfigured schema, so that you can only focus on the code and business logic.  So let’s get started! Prerequisites Command Line First In order to use the React CLI (create-react-app), it is good to grasp the command line first. It is used in many ways such as starting the application with create-react-app or using development scripts or building projects. Installing Node We will be using the Node package manager (npm) to start or create an application, so we will need to have Node installed on our computer.   To check if you have Node installed in your computer, run the below command in your terminal:node -vIf you have Node installed already in your system, this command will return a version number, like v12.18.2, and if it’s not installed already, kindly follow the mentioned steps in Setting Up Node Locally before moving on the next step. What comes up with create-react-app? So many developers use create-react-app as an easy starting kit for creating their React app. But surprisingly, many of them do not know about what comes in the starter kit, or how we can utilize it, or why it is even there! Let’s take a deep dive and see what’s under the hood!  It provides us with a recommended starting folder structure.  my-app/  //Dummy App Name   README.md   node_modules/   package.json   public/     index.html     favicon.ico   src/     App.css     App.js     App.test.js     index.css     index.js     Logo.svgScripts to run our React application   These scripts are  normally used to start, run or test the React application. (We will learn about these scripts later in our article) Extensibility Ability to extend with Sass, TypeScript, Charts, and more other libraries. A solid build setup with webpack and Babel Scripts to bundle for production ...and much more! Steps To Run the Application:  Now that we have some context about the Create React App and its usage, let’s not waste more time and get started by installing it. There are only 3 steps to create and run the application: npm init react-app my-new-app npm start npm run build Let’s discuss each one of them in detail. Step-1: Installing and Creating a create-react-app  Though it is quite possible to manually create a new React app also, the Facebook community had already created a Node package for create-react-app to generate a boilerplate version of a React application to make our life easier. There are many ways to install create-react-app. We can use any of them as per our ease. # using npm (npm 6+) # using npx (npm 5.2+) or, # using yarn (yarn 0.25+) Installing create-react-app What are you waiting for…? Let’s open up the terminal and run the below command: // Using npm  npm init react-app my-new-app   // my-new-app is the app name We can choose any name in the place of “my-new-app”, with only lowercase letters. Note:  If you’ve already installed create-react-app globally via npm install -g create-react-app, it is recommended that you uninstall the package first. Run the below command to uninstall the same. npm uninstall -g create-react-app  Once the above step is completed, you will get some quick generic tips on how to use this application: # npm start # npm run build  # npm test # npm run eject Let's now explore what all we can do with our new application.Step 2: Running the Application Using React Scripts In our React project we can run some scripts which are useful for the following tasks: Running our application for development  Building our application for production  Testing our application if we've created any tests in our project Scripts are located inside the package.json, which you can see inside the project folder. //package.json file showing scripts block "scripts": {     "start": "react-scripts start",     "build": "react-scripts build",     "test": "react-scripts test",     "eject": "react-scripts eject"   },All the above scripts can be run by using the following commands.// To start our app for development npm start npm run start yarn start   // To build our app for production npm run production yarn production   // To test our application npm run test   // To Eject our application npm run ejectStarting the React App We can use the “start” command to start our application for development. Use the below command to run the application. npm run start  This command will start a local server (http://localhost:3000) and will open our application for the development in the browser, as shown below:  Say Hello World Let’s modify this text a bit, and display hello world. Open the file “App.js” from src folder in your editor. Delete the div named App-header! And instead add a new element like Hello world in App.js and save the file.  It should look like this.And that’s it. You have just now created your first React application. No Build Setup    In order to transpile our ES6 code to something that all browsers can read, a webpack or compiler is required.  Fortunately, Create React App is all configured with webpack and Babel so you don't have to manually set up anything. Bundling for Production Now let’s host our application for users. In order to do so, we need to bundle up all of our code into a few JavaScript files that the browser can load and users can see the running application. There is again a convenient script given by Create-react-App. Let's run the following command and see how build files get created. // (Bundling this app for production for external servers)  npm run build Once build is finished, there we have a new directory called build/ inside our project.   Inside the build folder, there is a file named index,html, and we can use the same file to host on the server. To be Noted: In order to build the project, these files must exist with the same filenames: public/index.html is the page template; src/index.js is the JavaScript entry point. Good To Know about your Build folder  >> Inside the build directory, you will find all the compiled and minified code which is put into the smallest usable state.  >> It doesn’t matter if it is readable or not, since this is not a public-facing piece of code. >> Inside the build/static directory are all the JavaScript and CSS files.  >> In each file inside of build/static there is a unique hash of the file contents. Conclusion Create React App is an awesome toolkit  for React developers. I hope you now understand the power of Create React App better.  As you have seen, there are lots of goodies that come with this toolkit. We can easily configure our own webpack and Babel setups as per our requirement. And if we want more support in terms of UI or to fulfill some business requirements we can easily add support for things like Sass or TypeScript. What are you waiting for? Fire that terminal up, install create-react-app, and start building your awesome ideas with this solid base! Happy Learning! 
9838
How to add React to an existing website?

React, originally created by Facebook, is a popul... Read More