Search

Steps to Add React to a Website

React allows you to quickly develop complex user interfaces and web applications by breaking them down into simple and manageable components. Tailormade for today’s ever-evolving world, React JS is one of the most sought-after web frameworks among industries and is a key component of their growth.  Note: This article is purely for beginners and hence the following process is NOT recommended for production sites. However, this will allow the reader to get a taste of React without delving into toolchains and complicated processes.  So, let’s get started. All of you are already aware of ReactJs, designed by Facebook, which is a popular open-source JavaScript library. It is used for writing rich and engaging frontend abstractions in fewer lines of code within a short time. One of the reasons why React is so popular is because of its rendering performance.  In this post, we will learn how to add React JS to our current website. This article will pave the way for you to quickly start coding with React JS or simply import React in your existing project. No, it’s not rocket science! You can simply add it in your html file, that too in 1 minute!  What, just 1 minute? As in, 60 seconds…..? Read on to know more! Add React in One Minute An essential simple website consists of 3 files: Html file Js file, and CSS file   React JS can be used in a normal index.html file with no npm or web-packs. Hard to believe?  Steps to Add ReactJs to an existing website:  Let’s not waste any more time and start editing our existing HTML page, which is called index.html. There is no requirement of any external libraries or any other tool, just a code editor, website folder holding all the above files and Internet Connection.  Step:1 Open the HTML file you want to edit and add a div on which you want to add the React implementation. For instance: (index.html) looks like this, see line number 12-13<!DOCTYPE html> <html>   <head>     <meta charset="UTF-8" />     <title>Steps To Add React to a Website </title>   </head>   <body>       <h2>Steps To Add React to a Website </h2>       <!-- We will put our React component inside this div. → Line 12     <div id="some_random_id"></div>     </body> </html>Provide a unique ID attribute to the div, as shown above. This will allow us to distinguish it from the element we want to implement.  Step:2 Add the Script Tags to the same HTML page before the </body> tag as shown below: (Same as above)  ...      <!-- To load React add the scripts. -->      <script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script>      <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script>      </body>  </html>Here, we have added the scripts to load/import the React library.  Step:3 Now add one more script, to load our component which is “some_random_id” in the above code. Let’s name the JS file as “my_component.js”. <!DOCTYPE html>  <html>    <head>      <meta charset="UTF-8" />      <title>Steps To Add React to a Website </title>    </head>    <body>        <h2>Steps To Add React to a Website </h2>      <div id="some_random_id"></div>        <script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script>      <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script>        <!-- To Load our React component. -->      <script src="my_component.js"></script>      </body>  </html>Step:4 Now, Create and open the file named my_component.js and paste the following code:  'use strict';  const e = React.createElement;  class myButton extends React.Component {    constructor(props) {      super(props);      this.state = { isliked: false };    }      render() {      if (this.state.isliked) {        return 'Yes I Really Like This.';      }        return e(        'button',        { onClick: () => this.setState({ isliked: true }) },        'Like Button'      );    }  }  const domContainer = document.querySelector('#some_random_id');  ReactDOM.render(e(myButton), domContainer);Here we have created a React component named myButton, and displayed a button inside it. Step:5 ???Step:6  ???No step 5 or 6! It’s done. React has been  successfully added to the project and you can check the output too. No step 5 or 6! It’s done. React has been  successfully added to the project and you can check the output too.Adding JSX in our ComponentsReact is added, now let’s jump to writing code in an easier manner.  Consider the following snippet: const element = <h1>Hello, Buddy!</h1>;What does this syntax look like? It’s neither a string nor an HTML. This is JSX, a simple extension to JavaScript. While it’s not mandatory to use JSX with React, most of the developers find it helpful while experimenting with UI. You will experience this yourself later.Let’s quickly try JSXJSX comes with full power, as of JavaScript. We will see this later. Let’s get started on JSX by simply adding the below script tag:<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>Or you can also use JSX by adding type="text/babel" in any <script> tag.Add JSX to our ProjectAdding JSX to the project is more like adding some preprocessors for which we really need to install Node. If it’s already installed, then ignore this step and if it’s not, then:Install Node from hereCheck if Node is successfully installed by quickly running the following command in the terminal:node -vAnd it should give some output as:v8.11.4Note: Version may be less than 8.11.4. Great, let’s move ahead and add JSX to our project: Head to your website folder in the terminal: Run npm init -y Run npm install babel-cli@6 babel-preset-react-app@3 (NPM is used here to install JSX preprocessor) Done?  Let’s Run it! Running JSX Preprocessor  Go to the same website folder in terminal Create a folder named src Go inside src in the terminal and run the following command:  npx babel --watch src --out-dir . --presets react-app/prod Move the file “my_component.js” to the src folder and the watcher will convert the preprocessed file to basic Javascript file which is readable for the browser.  If you want to play around these preprocessors, head over here. Simple Example to See JSX: Let’s say we have a variable called title, we will see how we can use it in JSX: const title = 'React Developer';In JSX, we use by wrapping it in curly braces as {title}const title = 'React Developer'; const element = <h1>Welcome, {title}</h1>;   ReactDOM.render(   element,   document.getElementById('root') );AJAX and APIs Call-in React For Our Component    React doesn’t have any inbuilt package for calling the API calls, as it is a standalone library that comes only with fetch() method. But while working on Web projects, we need to render data somehow, either by local data or from server data. There are plenty of libraries by which we can make API calls, and we can choose any of them depending upon our project. Some of them are Fetch Axios React-Axios Use-Http React-request and more. Let’s go ahead with basic simple and index(0)th option, which is Fetch.  Trust me, you can choose any of them! Using Fetch to Make HTTP Calls in React Fetch() is a modern method and a browser-based API which is commonly used to make HTTP calls. The standard syntax of the Fetch API looks like: let response = fetch(     API_URL,     …. (some more options) );Here, API_URL is the URL using which we want to fetch the data from the server, and the URL comes with other arguments also depending upon the type of request (GET, PUSH, PUT,.. etc). The API returns with a promise which gets resolved into the response object once the response is fetched from the server. async getNames() {      // Calling some additional headers      const response = await       // Dummy API Data  fetch("https://jsonplaceholder.com/users", {        method: "GET", // *Type of request GET, POST, PUT, DELETE        mode: "cors", // Type of mode of the request        cache: "no-cache", // options like default, no-cache, reload, force-cache        headers: {          "Content-Type": "application/json" // request content type        },        credentials: "same-origin", // options like include, *same-origin, omit        redirect: "follow", // manual, *follow, error        referrerPolicy: "no-referrer", // no-referrer, *client        // body: JSON.stringify(data) // Attach body with the request      });        this.setState({ names: await response.json() });    } Here we have called a function named getNames, which fetches the data along with other parameters like: Method: what type of HTTP call is there, Header: to define request headers for authorization or content Mode: defines the type od mode, cors or no-cors,  As per official documentation: (Cross-Origin Resource Sharing (CORS) is a mechanism that uses additional HTTP headers to tell browsers to give a web application running at one origin, access to selected resources from a different origin.) Read about CORS here  Body: to send some additional data to the server as a request body Based on the requirement, we can call the desired options. And we can also use catch for managing errors while making API calls. async getNames() {      // With .then and .catch section      let response = await fetch("https://jsonplaceholder.com/users")        .then(response => {          return response.json();        this.setState({ names: response })        })        .catch(error => {          console.log(error);        });    } This is how we can use Fetch to make API calls, and do further operations in React.ConclusionIn this article, we learned how to add a React component in an HTML file or an existing website. You can follow the same steps to your own website, or if you want to have a fresh start you can simply create an empty HTML file to get started with React. We also saw how we can use JSX in our project and also played around with basic Http calls in React. I hope this article was helpful in getting started with React.  Happy Learning!

Steps to Add React to a Website

6K
Steps to Add React to a Website

React allows you to quickly develop complex user interfaces and web applications by breaking them down into simple and manageable components. Tailormade for today’s ever-evolving world, React JS is one of the most sought-after web frameworks among industries and is a key component of their growth.  

Note: This article is purely for beginners and hence the following process is NOT recommended for production sites. However, this will allow the reader to get a taste of React without delving into toolchains and complicated processes.  

So, let’s get started. 

All of you are already aware of ReactJs, designed by Facebook, which is a popular open-source JavaScript library. It is used for writing rich and engaging frontend abstractions in fewer lines of code within a short time. One of the reasons why React is so popular is because of its rendering performance.  

In this post, we will learn how to add React JS to our current website. This article will pave the way for you to quickly start coding with React JS or simply import React in your existing project. 

No, it’s not rocket science! You can simply add it in your html file, that too in 1 minute!  

What, just 1 minute? As in, 60 seconds…..? 

Read on to know more! 

Add React in One Minute 

An essential simple website consists of 3 files: 

  • Html file 
  • Js file, and 
  • CSS file  

 React JS can be used in a normal index.html file with no npm or web-packs. Hard to believe?  

Steps to Add ReactJs to an existing website:  

Let’s not waste any more time and start editing our existing HTML page, which is called index.html. There is no requirement of any external libraries or any other tool, just a code editor, website folder holding all the above files and Internet Connection.  

Step:1 Open the HTML file you want to edit and add a div on which you want to add the React implementation. 

For instance: (index.html) looks like this, see line number 12-13

<!DOCTYPE html> 
<html> 
  <head> 
    <meta charset="UTF-8" /> 
    <title>Steps To Add React to a Website </title> 
  </head> 
  <body> 
  
    <h2>Steps To Add React to a Website </h2> 
  
    <!-- We will put our React component inside this div. → Line 12 

    <div id="some_random_id"></div> 
  
  </body> 
</html>

Provide a unique ID attribute to the div, as shown above. This will allow us to distinguish it from the element we want to implement.  

Step:2 Add the Script Tags to the same HTML page before the </body> tag as shown below: 

(Same as above) 
... 
    <!-- To load React add the scripts. --> 
    <script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script> 
    <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script> 
 
  </body> 
</html>

Here, we have added the scripts to load/import the React library.  

Step:3 Now add one more script, to load our component which is “some_random_id” in the above code. Let’s name the JS file as “my_component.js”. 

<!DOCTYPE html> 
<html> 
  <head> 
    <meta charset="UTF-8" /> 
    <title>Steps To Add React to a Website </title> 
  </head> 
  <body> 
 
    <h2>Steps To Add React to a Website </h2> 
    <div id="some_random_id"></div> 
 
    <script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script> 
    <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script> 
 
    <!-- To Load our React component. --> 
    <script src="my_component.js"></script> 
 
  </body> 
</html>

Step:4 Now, Create and open the file named my_component.js and paste the following code:  

'use strict'; 
const e = React.createElement; 
class myButton extends React.Component { 
  constructor(props) { 
    super(props); 
    this.state = { isliked: false }; 
  } 
 
  render() { 
    if (this.state.isliked) { 
      return 'Yes I Really Like This.'; 
    } 
 
    return e( 
      'button', 
      { onClick: () => this.setState({ isliked: true }) }, 
      'Like Button' 
    ); 
  } 
} 
const domContainer = document.querySelector('#some_random_id'); 
ReactDOM.render(e(myButton), domContainer);

Here we have created React component named myButton, and displayed a button inside it. 

Step:5 ???

Step:6  ???

No step 5 or 6! It’s done. React has been  successfully added to the project and you can check the output too. 

No step 5 or 6! It’s done. React has been  successfully added to the project and you can check the output too.

Adding JSX in our Components

React is added, now let’s jump to writing code in an easier manner.  

Consider the following snippet: 

const element = <h1>Hello, Buddy!</h1>;

What does this syntax look like? It’s neither a string nor an HTML. This is JSX, a simple extension to JavaScript. While it’s not mandatory to use JSX with React, most of the developers find it helpful while experimenting with UI. You will experience this yourself later.

Let’s quickly try JSX

JSX comes with full power, as of JavaScript. We will see this later. Let’s get started on JSX by simply adding the below script tag:

<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>

Or you can also use JSX by adding type="text/babel" in any <script> tag.

Add JSX to our Project

Adding JSX to the project is more like adding some preprocessors for which we really need to install Node. If it’s already installed, then ignore this step and if it’s not, then:

Install Node from here

Check if Node is successfully installed by quickly running the following command in the terminal:

node -v

And it should give some output as:

v8.11.4

Note: Version may be less than 8.11.4. 

Great, let’s move ahead and add JSX to our project: 

  1. Head to your website folder in the terminal: 

  1. Run npm init -y 

  1. Run npm install babel-cli@6 babel-preset-react-app@3 (NPM is used here to install JSX preprocessor) 

Done?  Let’s Run it! 

Running JSX Preprocessor  

  1. Go to the same website folder in terminal 
  2. Create a folder named src 
  3. Go inside src in the terminal and run the following command:  
npx babel --watch src --out-dir . --presets react-app/prod

Move the file “my_component.js” to the src folder and the watcher will convert the preprocessed file to basic Javascript file which is readable for the browser.  

If you want to play around these preprocessors, head over here. 

Simple Example to See JSX: 

Let’s say we have a variable called title, we will see how we can use it in JSX: 

const title = 'React Developer';

In JSX, we use by wrapping it in curly braces as {title}

const title = 'React Developer'; 
const element = <h1>Welcome, {title}</h1>; 
  
ReactDOM.render( 
  element, 
  document.getElementById('root') 
);

AJAX and APIs Call-in React For Our Component    

React doesn’t have any inbuilt package for calling the API calls, as it is a standalone library that comes only with fetch() method. But while working on Web projects, we need to render data somehow, either by local data or from server data. 

There are plenty of libraries by which we can make API calls, and we can choose any of them depending upon our project. Some of them are 

  • Fetch 
  • Axios 
  • React-Axios 
  • Use-Http 
  • React-request and more. 

Let’s go ahead with basic simple and index(0)th option, which is Fetch.  Trust me, you can choose any of them! 

Using Fetch to Make HTTP Calls in React 

Fetch() is a modern method and a browser-based API which is commonly used to make HTTP calls. The standard syntax of the Fetch API looks like: 

let response = fetch( 
    API_URL, 
    …. (some more options) 
);

Here, API_URL is the URL using which we want to fetch the data from the server, and the URL comes with other arguments also depending upon the type of request (GET, PUSH, PUT,.. etc). 

The API returns with a promise which gets resolved into the response object once the response is fetched from the server. 

async getNames() { 
    // Calling some additional headers 
    const response = await  
    // Dummy API Data 
fetch("https://jsonplaceholder.com/users", { 
      method: "GET", // *Type of request GET, POST, PUT, DELETE 
      mode: "cors", // Type of mode of the request 
      cache: "no-cache", // options like default, no-cache, reload, force-cache 
      headers: { 
        "Content-Type": "application/json" // request content type 
      }, 
      credentials: "same-origin", // options like include, *same-origin, omit 
      redirect: "follow", // manual, *follow, error 
      referrerPolicy: "no-referrer", // no-referrer, *client 
      // body: JSON.stringify(data) // Attach body with the request 
    }); 
 
    this.setState({ names: await response.json() }); 
  } 

Here we have called a function named getNames, which fetches the data along with other parameters like: 

  • Method: what type of HTTP call is there, 
  • Header: to define request headers for authorization or content 
  • Mode: defines the type od mode, cors or no-cors,  

As per official documentation: 

(Cross-Origin Resource Sharing (CORS) is a mechanism that uses additional HTTP headers to tell browsers to give a web application running at one origin, access to selected resources from a different origin.) 

Read about CORS here  

  • Body: to send some additional data to the server as a request body 

Based on the requirement, we can call the desired options. And we can also use catch for managing errors while making API calls. 

async getNames() { 
    // With .then and .catch section 
    let response = await fetch("https://jsonplaceholder.com/users") 
      .then(response => { 
        return response.json(); 
      this.setState({ names: response }) 
      }) 
      .catch(error => { 
        console.log(error); 
      }); 
  } 

This is how we can use Fetch to make API calls, and do further operations in React.

Conclusion

In this article, we learned how to add a React component in an HTML file or an existing website. You can follow the same steps to your own website, or if you want to have a fresh start you can simply create an empty HTML file to get started with React. We also saw how we can use JSX in our project and also played around with basic Http calls in React. 

I hope this article was helpful in getting started with React.  

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

What are React Component Lifecycle Methods

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

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

What are the Pros and Cons of React

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

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

What is query string in Node.js?

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

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