Search

5 REASONS TO LEARN REACT-JS IN 2020-2021

If you have been learning or using JavaScript you have probably heard of React.  Among the most popular JavaScript libraries, ReactJS brings with it rich features that make it an easy to use and popular tool among developers. React libraries are growing at an enormous rate, helping developers in building rich efficient front-end abstractions by writing less code and in lesser time as well! Add to that the abundance of ReactJS jobs that make React expertise a hot commodity. Mastering React can help you build a solid career in the field of development.The growth of React since its inception has been phenomenal. No front-end framework has grown as much as React has in such a short time, showing the extent of its popularity in the developing community. It has consistently been rated as being among the top most used frameworks.In this article, we will learn about why you should start learning ReactJS, how React has transformed the world of WEB and much more.Let’s get started and see the power of React!Why should I use React? Let’s first understand about the various components of a webpage.  We use HTML for writing the markup ,CSS for the presentation of the markup and we use JavaScript to put all the logic for rendering dynamic Webpages. So, to build a simple web page, we can use the HTML-CSS-JS concept. But what about an application that has multiple features, and every feature or component is interrelated to each other?This is where we get to use the magic of React! React will help to create stable-optimized web apps. As the need for all third-party libraries is fading, React is emerging as a one-in-all- solution, and with its huge capabilities in solving almost all types of problems. (Go and check out the React community here 5 Advantages Of ReactJs (Why is it everyone’s favorite?)  You must be thinking, there are so many JavaScript frameworks out there. Why should I prefer React over the others, and how does React help in overcoming x-y-z problems?There are a tonne of reasons for learning and adapting React as your preferred JavaScript library. Listed below are some of them. 1. The era of Reusable Components: The very basic and the most important thing you need to know about React is the Component. React is nothing but one large pile of big components which call other small components.  While handling big applications using React, we use encapsulation. An application written in React is basically a composition of smaller React components holding some state that can be reused anywhere multiple times.  Let’s see the practical view of the above example: function clickHandler(e) { // Some function where some API call happens dummyApiCall(e.target.value); }   function MyBtn() { return (    <button className="button" onClick={clickHandler}>      Click Me    </button> ); }Let’s say we have a button name “Click Me”, and we want to use this button with the same logic (click handler) multiple times in our application, we can simply reuse the MyBtn component multiple times inside our Main application:function Main() { return (    <div className="main">      <MyBtn />    </div>    <p>Click to know More        <MyBtn />    </p> ); }Similarly, we can use so many reusable components in our application by providing a generic logic to the component so that it can be reused easily.Cool, isn't it? React components are a great way of using encapsulation. Just create a component and use it wherever needed. React component-based structure has proven its power not only for dynamic sites but also for content-based sites.2. Patterns of ReactThe basic declarative approach is focused on WHAT needs to be done, instead of the instructions on how it must be done.   Declarative code is useful for making the code more predictable and easier to debug.   With React-based projects, you don’t tell React how to organize the state, you just tell React ‘I need that state’ and you can rely on React for getting and setting up the state data. Also, at a higher level, with the help of React, we can achieve global state management which is typically using some common data logic in the entire system, such as: User profile data, or Theme Data, or   User Journey Data     With React we can create interactive UIs with a declarative approach and also design simple views for each and every state in our application. You can rely on React for efficiently updating and rendering the right components when the data changes. Before ReactJS entered the stage, it was very difficult to create dynamic web applications. ReactJS has simplified this process with the help of a JavaScript Extension known as JSX. It makes machine-readable codes easier.  And it’s very cool and easy to scale the React application.   Still have doubts? Just begin with a small MVP in React and you can scale it to a level that’s as far and as complex as Facebook :) That’s the beauty of React!3. Backward compatibilityWhenever a new version is updated in React, it only increases the ease of use for us and the public APIs remain the same. This means we need not worry about updating our application with any new releases of React as the base APIs remain constant.  This means that you do not have to learn a new version after every update. The old version remains the same, constant, and compatible with the newly added components.  In a practical context, React 16 maintains the exact same public API as in the (15.x and earlier) previous versions.4. Concurrent ModeWhat is Concurrent mode?All of us would have definitely experienced this.  Whenever we use an autocomplete form there is a freeze of the cursor at times, mostly seen in React applications because of its rendering behavior. For example, take a look at the below diagram. When we try to type “WAIT”, with every key event triggered, UI gets blocked on updating it.This performance degradation problem can also be solved by debouncing or throttling but that is not really suggested. There is another way to address this problem, which is by using the concurrent mode. As per React official docs:  Concurrent Mode is a set of new features that help React apps stay responsive and gracefully adjust to the user’s device capabilities and network speed. In Concurrent mode, there is no blocking in the rendering which improves the user experience and hence enables a few new features which were not easy to use earlier. In other words, if we have different branches in GIT, and all the developers can work on separate different branches without hindering or blocking anyone, in the same manner, React can work in different updates of states concurrently.  Yet again React makes a developers’ life simple by providing an easy and fast approach for  rendering an application.  One exciting feature of Concurrent Mode is Suspense. With this, you don’t have to wait for the response to render something in the application. <Suspense> Component can fetch the data in a declarative manner which can help in improving the user experience.  Want to know more? Click the link here.5. SEO Friendly Framework Most of our applications require ranking to mark their presence, and Google achieves this ranking with the use of bots. SEO is a technique to boost user traffic where all the crawling and indexing is done by these Bots.  Search Engines hate heavy JavaScript pages because of reading troubles when the page is loaded in the browser. Also, if the basic HTML page contains nothing but some meta tags and script tags, the search engine will assume that our page is blank and the result is you get a poor ranking.React has a pre-rendering feature that helps in getting an SEO friendly platform in both SPAs or multiple page applications.  Also, in React we can achieve server-side rendering very easily in contrast to the older JavaScript-based applications where we have to make use of external third-party libraries.  Since JS pages are heavy, crawlers take more time to crawl a page, whereas in React, a page comes as a single web page with the help of Virtual DOM.  Outlined above are just some of the basic React features. There are still tonnes of advantages of React, covered in the following pointers:Easy to use and easy to learnPerformance and reusabilityLess Development timeAn amazing Ecosystem, dev tools, and new frameworksSingle codebase, multiple viewsAbility to build MVP features in a scalable and faster mannerComponent oriented approachPerformance and reusabilityConclusion  By now, you have a clear idea about why there is such a demand for React developers and for React as a framework.  React is definitely a great tool for developing apps with bite-sized components that are easy-to-understand. One of React’s best features is managing the state for the components. You may have understood how React is helping developers write cleaner, lesser and more scalable code.  There’s a lot more to read if you want to know how to use React to transform the way web Apps are built.  For further reading or research, I suggest you deep dive into the projects written in React from scratch by the React community.  Happy Learning!  

5 REASONS TO LEARN REACT-JS IN 2020-2021

7K
5 REASONS TO LEARN REACT-JS IN 2020-2021

If you have been learning or using JavaScript you have probably heard of React.  Among the most popular JavaScript libraries, ReactJS brings with it rich features that make it an easy to use and popular tool among developers. React libraries are growing at an enormous rate, helping developers in building rich efficient front-end abstractions by writing less code and in lesser time as well! Add to that the abundance of ReactJS jobs that make React expertise a hot commodity. Mastering React can help you build a solid career in the field of development.

The growth of React since its inception has been phenomenal. No front-end framework has grown as much as React has in such a short time, showing the extent of its popularity in the developing community. It has consistently been rated as being among the top most used frameworks.

In this article, we will learn about why you should start learning ReactJS, how React has transformed the world of WEB and much more.

Let’s get started and see the power of React!

Why should I use React?

 Let’s first understand about the various components of a webpage.  

We use HTML for writing the markup ,CSS for the presentation of the markup and we use JavaScript to put all the logic for rendering dynamic Webpages. So, to build a simple web page, we can use the HTML-CSS-JS concept. But what about an application that has multiple features, and every feature or component is interrelated to each other?

Why should I use React?

This is where we get to use the magic of React! React will help to create stable-optimized web apps. As the need for all third-party libraries is fading, React is emerging as a one-in-all- solutionand with its huge capabilities in solving almost all types of problems. 

(Go and check out the React community here

 5 Advantages Of ReactJs (Why is it everyone’s favorite?)  

You must be thinking, there are so many JavaScript frameworks out there. Why should I prefer React over the others, and how does React help in overcoming x-y-z problems?

5 Advantages Of ReactJs

There are a tonne of reasons for learning and adapting React as your preferred JavaScript library. Listed below are some of them. 

1. The era of Reusable Components: 

The very basic and the most important thing you need to know about React is the Component. React is nothing but one large pile of big components which call other small components.  

While handling big applications using React, we use encapsulation. An application written in React is basically a composition of smaller React components holding some state that can be reused anywhere multiple times.  

Let’s see the practical view of the above example: 

function clickHandler(e) { 
// Some function where some API call happens 
dummyApiCall(e.target.value); 
} 
  
function MyBtn() { 
return ( 
   <button className="button" onClick={clickHandler}> 
     Click Me 
   </button> 
); 
}

Let’s say we have a button name “Click Me”, and we want to use this button with the same logic (click handler) multiple times in our application, we can simply reuse the MyBtn component multiple times inside our Main application:

function Main() { 
return ( 
   <div className="main"> 
     <MyBtn /> 
   </div> 

   <p>Click to know More   

     <MyBtn /> 

   </p> 
); 
}

Similarly, we can use so many reusable components in our application by providing a generic logic to the component so that it can be reused easily.

Cool, isn't it? React components are a great way of using encapsulation. Just create a component and use it wherever needed. React component-based structure has proven its power not only for dynamic sites but also for content-based sites.

2. Patterns of React

The basic declarative approach is focused on WHAT needs to be done, instead of the instructions on how it must be done.  

Declarative code is useful for making the code more predictable and easier to debug.  

With React-based projects, you don’t tell React how to organize the state, you just tell React ‘I need that state’ and you can rely on React for getting and setting up the state data. Also, at a higher level, with the help of React, we can achieve global state management which is typically using some common data logic in the entire system, such as:

  1. User profile data, or
  2. Theme Data, or  
  3. User Journey Data     

With React we can create interactive UIs with a declarative approach and also design simple views for each and every state in our application.

You can rely on React for efficiently updating and rendering the right components when the data changes.

Before ReactJS entered the stage, it was very difficult to create dynamic web applications. ReactJS has simplified this process with the help of a JavaScript Extension known as JSX. It makes machine-readable codes easier. 

 
And it’s very cool and easy to scale the React application.  

Still have doubts? 

Just begin with a small MVP in React and you can scale it to a level that’s as far and as complex as Facebook :) That’s the beauty of React!

3. Backward compatibility

Whenever a new version is updated in React, it only increases the ease of use for us and the public APIs remain the same. This means we need not worry about updating our application with any new releases of React as the base APIs remain constant.  

This means that you do not have to learn a new version after every update. The old version remains the same, constant, and compatible with the newly added components.  

In a practical context, React 16 maintains the exact same public API as in the (15.x and earlier) previous versions.

4. Concurrent Mode

What is Concurrent mode?

All of us would have definitely experienced this.  

Whenever we use an autocomplete form there is a freeze of the cursor at times, mostly seen in React applications because of its rendering behavior. For example, take a look at the below diagram. When we try to type “WAIT”, with every key event triggered, UI gets blocked on updating it.

What is Concurrent mode?

This performance degradation problem can also be solved by debouncing or throttling but that is not really suggested. 

There is another way to address this problem, which is by using the concurrent mode. 

As per React official docs:  

Concurrent Mode is a set of new features that help React apps stay responsive and gracefully adjust to the user’s device capabilities and network speed. 

In Concurrent mode, there is no blocking in the rendering which improves the user experience and hence enables few new features which were not easy to use earlier. In other words, if we have different branches in GIT, and all the developers can work on separate different branches without hindering or blocking anyone, in the same manner, React can work in different updates of states concurrently.  

Yet again React makes a developers’ life simple by providing an easy and fast approach for  rendering an application.  

One exciting feature of Concurrent Mode is Suspense. With this, you don’t have to wait for the response to render something in the application. 

<Suspense> Component can fetch the data in a declarative manner which can help in improving the user experience.  

Want to know more? Click the link here.

5. SEO Friendly Framework 

Most of our applications require ranking to mark their presence, and Google achieves this ranking with the use of bots. SEO is a technique to boost user traffic where all the crawling and indexing is done by these Bots.  

Search Engines hate heavy JavaScript pages because of reading troubles when the page is loaded in the browser. Also, if the basic HTML page contains nothing but some meta tags and script tags, the search engine will assume that our page is blank and the result is you get a poor ranking.

React has a pre-rendering feature that helps in getting an SEO friendly platform in both SPAs or multiple page applications.  

Also, in React we can achieve server-side rendering very easily in contrast to the older JavaScript-based applications where we have to make use of external third-party libraries.  Since JS pages are heavy, crawlers take more time to crawl a page, whereas in React, a page comes as a single web page with the help of Virtual DOM.  

Outlined above are just some of the basic React features. There are still tonnes of advantages of React, covered in the following pointers:

  • Easy to use and easy to learn
  • Performance and reusability
  • Less Development time
  • An amazing Ecosystem, dev tools, and new frameworks
  • Single codebase, multiple views
  • Ability to build MVP features in a scalable and faster manner
  • Component oriented approach
  • Performance and reusability

Conclusion  

By now, you have a clear idea about why there is such a demand for React developers and for React as a framework.  

React is definitely a great tool for developing apps with bite-sized components that are easy-to-understand. One of React’s best features is managing the state for the components. You may have understood how React is helping developers write cleaner, lesser and more scalable code.  

There’s a lot more to read if you want to know how to use Reacto transform the way web Apps are built.  For further reading or research, I suggest you deep dive into the projects written in React from scratch by the React community 

Happy Learning!  

KnowledgeHut

KnowledgeHut

Author

KnowledgeHut is an outcome-focused global ed-tech company. We help organizations and professionals unlock excellence through skills development. We offer training solutions under the people and process, data science, full-stack development, cybersecurity, future technologies and digital transformation verticals.
Website : https://www.knowledgehut.com

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

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 CodeOnce 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.
4507
Instal React Js on Windows

IntroductionIn this tutorial, we will learn how to... 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