React JS

SAMEER MISTRY
9 min readMay 10, 2021

WHAT IS REACT ?

ReactJS often referred to as React or ReactJS is a JavaScript library responsible for building a hierarchy of UI components or in other words, responsible for the rendering of UI components. It provides support for both front-end and server-side.

ReactJS is just the V part of the MVC framework, a library meant for rendering your views.

ReactJS creates an in-memory data structure cache

One of the unique feature of React.js is not only it can perform on the client side but it can also be rendered on the server side and they can work together interoperable.

Prerequisites

Before learning ReactJS in-depth, you must have a good knowledge of JavaScript, HTML5, and CSS. The knowledge of ECMAScript 2015 syntax can also be helpful.

Ref : ECMAScript 2015(ES6)

React Features

  • JSX

JSX stands for JavaScript XML. It is a JavaScript syntax extension. Its an XML or HTML like syntax used by ReactJS. This syntax is processed into JavaScript calls of React Framework.

  • Components

Components are independent and reusable bits of code.

Conceptually, components are like JavaScript functions that return HTML elements.

  • One-way Data Binding

React implements one-way data flow which makes it easy to reason about your app. Flux is a pattern that helps keeping your data unidirectional.

  • Virtual DOM

The virtual DOM is used for efficient re-rendering of the DOM.Whenever any modifications happen in the web application, the entire UI is re-rendered in virtual DOM representation.

React Environment Setup

There are two ways to set up an environment for successful ReactJS application. They are given below:

  1. Using the npm command
  2. Using the create-react-app command

1)Using the npm command:

  • Install NodeJS and NPM

You can install NodeJS and NPM package manager by the link given below.

Ref : https://www.javatpoint.com/install-nodejs-on-linux-ubuntu

Ref : https://www.javatpoint.com/install-nodejs

  • Install React and React DOM

mkdir react_app

cd react_app

Create a package.json file. To create any module, it is required to generate a package.json file in the project folder. To do this, you need to run the following command as shown below .

npm init -y

After creating a package.json file, you need to install react and its DOM packages using the following npm command in the terminal as shown below:

npm install react — save

npm install react-dom — save

  • Install WebPack

Ref: https://sameermistry2502.medium.com/reactjs-babel-and-webpack-f2491dc9f685

  • Install Babel

Ref: https://sameermistry2502.medium.com/reactjs-babel-and-webpack-f2491dc9f685

2)Using the npm command:

The ‘create-react-app’ is a tool maintained by Facebook itself. This is suitable for beginners without manually having to deal with transpiling tools like webpack and babel. In this section, I will be showing you how to install React using CRA(create-react-app) tool.

npm install -g create-react_app

Create a new React project:

create-react-app react_app

You can combine the above two steps in a single command using npx. The npx is a package runner tool that comes with npm 5.2 and above version

npx create-react-app react_app

Running the Server:

Go to folder path : cd folder_name then run below command:

npm start

Default React App

Generating the bundle you need to run the build command:

npm run build

React Folder Structure

JSX

JSX stands for JavaScript XML.JSX allows us to write HTML in React.It makes easier to write and add HTML in React.

JSX converts HTML tags into react elements.

Example1:-

  • index.js
import React from 'react';
import ReactDOM from 'react-dom';

const myelement = <h1>Value count is {10 + 5} with JSX</h1>;

ReactDOM.render(myelement, document.getElementById('root'));
  • index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport"
content="width=device-width, initial-scale=1" />
<title>React App</title>
</head>
<body>

<div id="root"></div>

</body>
</html>

Output : -

Components

Components are independent and reusable bits of code.Conceptually, components are like javascript functions that return HTML elements.

Earlier, the developers write more than thousands of lines of code for developing a single page application. These applications follow the traditional DOM structure, and making changes in them was a very challenging task. If any mistake found, it manually searches the entire application and update accordingly.

The component-based approach was introduced to overcome an issue. In this approach, the entire application is divided into a small logical group of code, which is known as components.

React Components
React Components Tree-View

There are two types of components in React:

  1. Class Component
  2. Functional Component

Class Component

A class component requires you to extend from React. Component and create a render function which returns a React element.class component is shown in the below:

class Home extends React.Component {render() {  return (    <div>Class component Called.</div>  ); }}

Example:

import React, { Component } from 'react';class App extends Component {constructor() {super();this.state = {data:[{"name":"Dr KK Shah","hospital":"KK Shah Nursing Home",'edu':'MD'},{"name":"Dr RJ Panchal","hospital":"Rudraksh Hospital","edu":'MD'},{"name":"Dr Janak Patel",'edu':'MBBS',"hospital":"JP Nursing Home",}]}}render() {return (<div><DRList/><ul>{this.state.data.map((item) => <List data = {item} />)}</ul></div>);}}class DRList extends Component {render() {return (<div><h1>Docter's List</h1></div>);}}class List extends React.Component {render() {return (<ul><li><h6>{this.props.data.name}</h6> ({this.props.data.edu})</li></ul>);}}export default App;

Output:

Functional Components

A functional component is just a plain JavaScript function that accepts props as an argument and returns a React element.There is no render method used in functional components.

Also known as Stateless components as they simply accept data and display them in some form, that they are mainly responsible for rendering UI.

Example:

import React from 'react';import ReactDOM from 'react-dom';const DRList=(props)=>{
let dr_list = props.data;
return (<ul><li><h6>{this.props.data.name}</h6> ({this.props.data.edu})</li><p>{this.props.data.hospital}</p></ul> )
}

Output:

State

  • React components has a built-in state object
  • The state object is where you store property values that belongs to the component.
  • State are mutable.
  • When the state object changes, the component re-renders.

Example:

class DrInfo extends Component {constructor(props) {super(props);this.state = { name: “Dr Kiran K Shah” ,edu:"MD"};}render() {return (<div><h1>My {this.state.name}</h1></div>);}}

Output:

Dr Kiran K Shah

Props

  • Props are arguments passed into React Components.
  • React Props are like function arguments in attributes in HTML.
  • Props are immutable.
  • Child component will receive data from parent component via props.

Example:

import React, { Component } from 'react';class App extends Component {constructor() {super();this.state = {hospital_info: ["SVP","SMS","KD","CIMS"]}}render() {return (<div><HList/><ul>{this.state.hospital_info.map((item) => <List data = {item} />)}</ul></div>);}}class HList extends React.Component {render() {return (<div><h1>Pivate Hospital List</h1></div>);}}class List extends React.Component {render() {return (<ul><li><h6>{this.props.data}</h6></li></ul>);}}export default App;

Output:

Lifecycle Methods of ReactJS

Each component in React has a lifecycle which you can monitor and manipulate during its three main phases.

  1. Initial Phase
  2. Mounting
  3. Updating
  4. Unmounting

Initial Phase

The initial phase only occurs once and consists of the following methods.

  • getDefaultProps()
    It is used to specify the default value of this.props. It is invoked before the creation of the component or any props from the parent is passed into it.
  • getInitialState()
    It is used to specify the default value of this.state. It is invoked before the creation of the component.

Mounting Phase

Mounting means putting elements into the DOM.React has four built-in methods that gets called, in this order, when mounting a component:

  1. constructor()
  2. getDerivedStateFromProps()
  3. render()
  4. componentWillMount()
  5. componentDidMount()
  • componentWillMount() is executed before rendering, on both the server and the client side.
  • componentDidMount() is executed after the first render only on the client side. This is where AJAX requests and DOM or state updates should occur.
  • The render() method is required and will always be called, the others are optional and will be called if you define them.

Updating Phase

Here, we get new Props and change State. This phase also allows to handle user interaction and provide communication with the components hierarchy.

  1. getDerivedStateFromProps()
  2. shouldComponentUpdate()
  3. render()
  4. getSnapshotBeforeUpdate()
  5. componentDidUpdate()
  6. componentWillUpdate()
  • shouldComponentUpdate() should return true or false value. This will determine if the component will be updated or not.
  • componentWillUpdate() is called just before rendering.
  • componentDidUpdate() is called just after rendering.

Unmounting Phase

  • In this phase componentWillUnmount() is called after the component is unmounted from the DOM.
LifeCycle Methods of ReactJS

Example:

import React, { Component } from 'react';class App extends Component {constructor(props) {super(props);this.state = {hospital_info: ""};   this.changeState = this.changeState.bind(this)}render() {if (this.state.hospital_info.length > 0 && this.state.hospital_info.length !== 0) {return (<div><h3>Hospital Details</h3><span>--------------------------------</span>{this.state.hospital_info.map((item) => <List data = {item} />)}</div>);} else {return (<div><h1>ReactJS component's Lifecycle</h1><h3>Show Hospital's Information</h3><button onClick = {this.changeState}>Click Here to get Details!</button></div>);}}componentWillMount() {console.log('Component Will MOUNT!')}componentDidMount() {console.log('Component Did MOUNT!')}changeState(){this.setState({hospital_info:[{"hospital":"Civil Hospital","location":"Asarwa, Ahmedabad, Gujarat 380016"},{"hospital":"KD Hospital","location":"Sardar Patel Ring Rd, Ahmedabad, Gujarat 382421"},{"hospital":"SMS Multi-Speciality Hospital","location":"Near Tapovan Circle, Visat - Gandhinagar Hwy, Chandkheda, Ahmedabad, Gujarat 382424"},{"hospital":"CIMS Hospital","location":"Science City Rd, Science City, Panchamrut Bunglows II, Sola, Ahmedabad, Gujarat 380060"},{"hospital":"Sola Civil Hospital","location":"Sola,S.G. Highway, Ahmedabad, Gujarat 380060"}]});}componentWillReceiveProps(newProps) {console.log('Component Will Recieve Props!')}shouldComponentUpdate(newProps, newState) {return true;}componentWillUpdate(nextProps, nextState) {console.log('Component Will UPDATE!');}componentDidUpdate(prevProps, prevState) {console.log('Component Did UPDATE!')}componentWillUnmount() {console.log('Component Will UNMOUNT!')}}class List extends React.Component {render() {return (<div style={{marginLeft:"20px"}}><h4>{this.props.data.hospital}</h4><p>{this.props.data.location}</p></div>);}}export default App;

Outout:

Pros and Cons of ReactJS

There are some various pros and cons of ReactJS given as following:

Pros(Advantages)

  • Creating Dynamic Web Applications Becomes Easier

It provides less coding and gives more functionality. It makes use of the JSX(JavaScript Extension)

  • Reusable Components

ReactJS application is made up of multiple components, and each component has its own logic and controls. These components are responsible for outputting a small, reusable piece of HTML code which can be reused wherever you need them. The reusable code helps to make your apps easier to develop and maintain.

  • Performance Enhancement

ReactJS improves performance due to virtual DOM. The DOM is a cross-platform and programming API which deals with HTML, XML or XHTML. Most of the developers faced the problem when the DOM was updated, which slowed down the performance of the application. ReactJS solved this problem by introducing virtual DOM.

  • Scope for Testing the Codes

ReactJS applications are extremely easy to test. It offers a scope where the developer can test and debug their codes with the help of native tools.

Cons(Disadvantages)

  • The high pace of development

The high pace of development has an advantage and disadvantage both. In case of disadvantage, since the environment continually changes so fast, some of the developers not feeling comfortable to relearn the new ways of doing things regularly. They need to be always updated with their skills and learn new ways of doing things.

  • View Part

ReactJS Covers only the UI Layers of the app and nothing else. So you still need to choose some other technologies to get a complete tooling set for development in the project.

Ref:https://github.com/sameermistry2502/ReactJS-CRUD-App

--

--