React js tutorial

Learn react js with examples and react js tutorial concepts like what is react js? how does react js works? advantages of react js, react js components, import/export in react js, refs in react js, lists in react js, keys in react js, routes in react js, flux in react js, etc.

Learn step by step react js with examples.

What is React JS?

React js is a JavaScript library created by Facebook. It was first created by Jordan Walke, a software engineer working at Facebook. It was first deployed on Facebook’s newsfeed in 2011 and later on Instagram.com in 2012.

React is currently one of the most popular JavaScript libraries. It is used for handling the view layer for web and mobile apps. ReactJS allows us to create reusable UI components.

React allows developers to create large web applications which can change data, without reloading the page. It is to be fast, scalable, and simple.

Why we should learn React JS?

  • React is easy to learn and easy to use. Anyone who comes from a JavaScript background can understand and start using React in a few days.
  • Instead of separating the markup and logic in separated files, React uses components for this purpose.
  • React views are typically rendered using components which contain additional components specified as custom HTML tags.
  • It uses Virtual DOM, which creates an in-memory data structure cache, enumerates the resulting differences, and then updates the browser’s displayed DOM efficiently.
  • ReactJS comes out as a stronger framework because of the ability to break down the complex UI and allowing users to work on individual components.
  • React uses one-way data binding and an application architecture called Flux controls the flow of data to components through one control point – the dispatcher.
  • Flux features actions which are sent through a central dispatcher to a store and changes to the store are propagated back to the view. When used with React, this propagation is accomplished through component properties.
  • We can use Browserify, Require JS, ECMAScript 6 modules which we can use via Babel, ReactJS-di to inject dependencies automatically.

How does React JS Works?

While building client-side apps, a team at Facebook developers realized that the DOM is slow. So, to make it faster, React implements a virtual DOM that is basically a DOM tree representation in Javascript.

So when it needs to read or write to the DOM, it will use the virtual representation of it. Then the virtual DOM will try to find the most efficient way to update the browser’s DOM.

Unlike browser DOM elements, React elements are plain objects and are easy to create. React DOM takes care of updating the DOM to match the React elements.

The reason for this is that JavaScript is very fast and it’s worth keeping a DOM tree in it to speed up its manipulation.

Advantages of React js

  • Using virtual DOM will improve apps performance since JavaScript virtual DOM is faster than the regular DOM.
  • React Can be used on client and server side as well as with other frameworks.
  • It makes easier for us to create templates.
  • React uses one-way data flow, so only changes to the data result in changes to the UI.

Setting up Development Environment for react js

To run any React application, we must have NodeJS installed in our PC. Follow the below steps to install NodeJs.

Step 1: Download and Install the latest version of NodeJs

Step 2: Run the below command in your terminal or command prompt to install the React Boilerplate.

npm i -g create-react-app

After running the above command, our terminal will show the Successfully installed React boilerplate message as shown in the below image:

npm i create react app
create a new react app

Step 3: Next Step Create an App using Below command will create an app named “react-sample“.

create react app
create react app

Step 4: Now Change our current directory “react-sample” using below command.

C:\Users\Bijay>cd react-sample

C:\Users\Bijay\react-sample>

Step 5: To start the development server, execute the below command:

npm start
Introduction to create react app
Introduction to create react app

After successfully running the above command your compiler will show the below message:

create react app tutorial
create react app tutorial

We can Open the project in visual studio code using below command:

code .

Let’s have a look at the directory created and opened in VS Code.

create react app example
create react app example

Now the development environment set up and ready.We will move ahead to start learning ReactJS development to make some use of it.

Create React App doesn’t handle backend logic or databases; it just creates a frontend build pipeline, so you can use it with any backend you want. Under the hood, it uses Babel and Webpack, but you don’t need to know anything about them.

When you’re ready to deploy to production, running npm run build will create an optimized build of your app in the build folder.

Introduction to JSX

Instead of using regular JavaScript, React code should be written in something called JSX. JSX is an XML syntax extension to JavaScript that also comes with the full power of ES6 (ECMAScript 2015).

Let us see a sample JSX code:

var element = <h1>Welcome to React.</h1>;

The above code snippet somewhat looks like HTML and it also uses a JavaScript-like variable but is neither of HTML or JavaScript, it is JSX. It is basically a syntax extension of regular JavaScript and is used to create React elements.

Just like HTML, JSX tags can have a tag name, attributes, and children. If an attribute is wrapped in curly braces, the value is a JavaScript expression.

React DOM Render:

The method ReactDom.render() is used to display HTML elements:

Example:

index.html: Let’s suppose our index.html file has the following statement inside it:

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

index.js : Copy and paste this code in “index.js” file.

import React from 'react';
import ReactDOM from 'react-dom';
  
var element = <h1>Welcome to React.</h1>; 
   
ReactDOM.render( 
    element,  
    document.getElementById("root") 
); 

output:

React DOM Render
React DOM Render

JSX Expressions:

In React we are allowed to use normal JavaScript expressions with JSX. Expressions can be used in JSX by wrapping them in curly {} braces.

Example:

import React from 'react';
import ReactDOM from 'react-dom';
  
var name="Bijay"; 
var element = <div> 
    <text>Hello {name},</text>
    <h2><i>Welcome to React.</i></h2></div>; 
   
ReactDOM.render( 
    element,  
    document.getElementById("root") 
);

output:

JSX Expression
JSX Expression

Attributes in ReactJs(JSX):

Instead of the normal naming convention of HTML, JSX uses camelcase convention for attributes.

For example, class in HTML becomes className in JSX.

The main reason behind this is that some of the attribute names in HTML like ‘class‘ are reserved keywords in JavaScripts. So, to avoid this problem, JSX uses the camel case naming convention for attributes.

We can also use custom attributes in JSX. The names of such custom attributes should be prefixed by data-.

Example: In the following example, we added data-customattribute as an attribute of the p element.

import React from 'react';
class App extends React.Component {
   render() {
      return (
         <div>
        <p data-customattribute = "somev-alue">Attributes in JSX!!!</p>
         </div>
      );
   }
}
export default App;

Styling:

React recommends using inline styles. When we want to set inline styles, we need to use camelCase syntax.

Example: The following example shows how to add “styles” inline to h1 element.

import React from 'react';
class App extends React.Component {
   render() {
      var styles = {    
         fontSize: 50,
         color:'blue'
      }
      return (
         <div>
            <h1 style = {styles}><i>Hello ReactJs!</i></h1>
         </div>
      );
   }
}
export default App;

Comments in React:

Comments in JSX begins with /* and ends with */. We can add comments in JSX by wrapping them in curly braces {}.

Syntax:

{/ * This is a comment in JSX * /}

Fragments in React:

Fragments were introduced in React and we can use them instead of the extraneous ‘div’ tag.

the main reason for using is fragment is a little bit faster than the ‘div’ tag and also, it takes less memory.

Example:

import React from 'react';
class App extends React.Component { 
  render() { 
    return ( 
      <React.Fragment>  
        <h3>Hi User,</h3> 
        <p>Welcome to TSinfo</p> 
      </React.Fragment> 
    ); 
  } 
} 
export default App;

Another shorthand also exists for the above method in which we make use of ‘<>‘ and ‘</>‘ instead of the ‘React.Fragment’.

Example:

import React from 'react';
class App extends React.Component { 
  render() { 
    return ( 
      <>  
        <h3>Hi User,</h3> 
        <p>Welcome to TSinfo</p> 
      </> 
    ); 
  } 
} 
export default App;

React js Components

A Component is one of the core building blocks of React. In other words, we can say that every application you will develop in React will be made up of pieces called components. Components make the task of building UIs much easier.

Components in React basically returns a piece of JSX code which tells what should be rendered on the screen. In React we mainly have two types of components:

Functional Components

A functional component is simply javascript functions that take a single parameter or props object and returns a React component. While declaring a functional component you can also use arrow functions.

Below example shows a valid functional component in React.

Example:

index.html: Let’s suppose our index.html file has the following statement inside it:

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

index.js:

In ReactDOM.render() method, we can call function name as Welcome() or <Welcome />.

import React from 'react';
import ReactDOM from 'react-dom';

function Welcome() {
    return <h1><i>Functional Components in React!</i></h1>;
  } 
ReactDOM.render( 
    <Welcome />,  
    document.getElementById("root") 
); 
React Functional Components
React Functional Components

Class Components

We can use javascript ES6 classes to create class-based components in React. While declaring a class component, you should extend React’s PureComponent or Component class. Then whatever you return from the render function will be showing on the screen.

It is an instance of a class derived from React.Component class. The class must implement a render() member function which returns a React component to be rendered, similar to return value of a functional component. In a class-based component, props are accessible via this.props.

Below example shows a valid class-based component in React.

Example:

index.html: Let’s suppose our index.html file has the following statement inside it:

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

index.js file: copy and paste this code in index.js file.

import React from 'react';
import ReactDOM from 'react-dom';
class Welcome extends React.Component { 
render() {
         return(<h1>Class Components in React!</h1>); }
} 
ReactDOM.render( 
    <Welcome />,  
    document.getElementById("root") 
); 

Output:

React Class Components
React Class Components

Note: The name of a component should always start with a capital letter. This is done to differentiate a component tag with HTML tags.

PureComponent in Class Component

PureComponent – a new way of implementing class-based components. It is a base class for React class-based components. It implements shouldComponentUpdate lifecycle method.

PureComponent is an advanced optimization technique. it makes your application faster and can also break your app if you are not careful.

To use PureComponent simply derive your class-based component from React.PureComponent instead of React.Component.

Syntax:

class className extends React.PureComponent {
//implemet code here
}

Why to use PureComponent:

Both functional-based and class-based components have the same downside: they always re-render when their parent component re-renders even if the props don’t change.

Also, class-based components always re-render when its state is updated (this.setState is called) even if the new state is equal to the old state.
Moreover, when a parent component re-renders, all of its children are also re-rendered, and their children too, and so on.

So, PureComponent stops the vicious re-rendering cycle and does not re-render unless its props and state change.

When to use PureComponent:

  • we want to avoid re-rendering cycles of your component when its props and state are not changed.
  • The state and props of your component are immutable.
  • We don’t plan to implement our own shouldComponentUpdate lifecycle method.

A simple component doesn’t compare the previous and next state instead of rendering the component whenever the “shouldComponentUpdate” method is called. But pure-component will do that.

Example:

index.html: Let’s suppose our index.html file has the following statement inside it:

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

App.js: Open App.js file, Implement pure component class here.

import React from 'react';
import PropTypes from 'prop-types';
class App extends React.PureComponent {    
    constructor(props) {  
      super(props);          
      this.state = {  
         state: "karnataka",  
      }  
   } 
   
   componentDidMount(){
       setInterval(()=>{
           this.setState(()=>{
               return { state: "karnataka"}
           })
       },1000)

       setInterval(()=>{
        this.setState(()=>{
            return { state: "Mumbai"}
        })
    },6000)
   }
   
   render() {  
       console.log('Main Component render '+Date.now());  
      return (  
          <div>    
         <h2>    
            {this.state.title}   
         </h2>    
         <p>Company Name: {this.props.companyName}</p>  
         <p>Location: {this.props.location}</p>  
         </div>  
      );    
   }      
}    
App.propTypes ={  
       companyName:PropTypes.string.isRequired,  
       location:PropTypes.string.isRequired  
   }  
  
App.defaultProps = {  
  companyName: 'TSinfo Technology',  
  location: 'Bangalore'  
};      
export default App;

Index.js: Open index.js file and import the App.js file here.

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
ReactDOM.render( 
    <App />, 
    document.getElementById('root')); 

Shallow Comparison

Pure Components do the Shallow comparison instead of deep comparison. Shallow comparison means when checking the previous state and props, if values are primitive types, then it only checks or compares their values. But props or state are complex types like an object and array, then it checks their reference type. In deep checking, instead of reference values are compared.

var companyObj=function(name)
		{this.name=name
		};
var obj=new companyObj('tsinfo');
var obj1=obj;
//compare both object
obj==obj1  //output: true
//create another object
var obj2=new companyObj('tsinfo')
//compare both object
obj1==obj2  //output: false  because in complex type object reference are checked that are not same in this case

//check the value of both object
 obj2.name==obj1.name  //output: true because in primitive type value are checked that are same in this case

Difference between functional and class-based components

  • The functional component also called Stateless Components.
  • A functional component is just a Javascript function that returns a React element.
  • You can use render, props and context APIs with a functional component.
  • Functional component can’t have state or lifecycle methods.
  • The class component also called Stateful components.
  • A class component is a React class. It can maintain its own state.
  • Class-based components can have lifecycle methods which can be used to perform various actions at specific points of the component lifecycle.
  • Class-based components can have refs to underlying DOM nodes.
  • Class-based components can use shouldComponentUpdate and PureComponent performance optimization techniques.
  • Always use the stateless components for visualizations and data formats, and use the stateful components when the component requires some interaction with either the client or server side.

Props and State in React js

Props in React Js

  • we use props to send data to components.
  • Every component is treated as a pure javascript function.
  • props are equivalent to parameters of a pure javascript function.
  • Props are immutable. Because these are developed in the concept of pure functions. In pure functions, we cannot change the data of parameters. So, also cannot change the data of a prop in ReactJS.

React js Component props( Properties)

React allows us to pass information to a Component using props (stands for properties). Props are basically kind of global variable or object.

The props can be accessed as shown below:

this.props.propName;

The ‘this.props‘ is a kind of global object which stores all of a component’s props. The propName, that is the names of props are keys of this object.

Example of Class based Component props:

Below is a sample program to illustrate how to pass and access props from a component:

Example:

index.html: Let’s suppose our index.html file has the following statement inside it:

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

index.js:

import React from 'react';
import ReactDOM from 'react-dom';

class DemoClassComponent extends React.Component{ 
    render(){ 
        return( 
  
                <div> 
                    {/*accessing information from props */} 
                    <h2>Hello {this.props.username}</h2> 
                    <h3>Welcome to TSInfo</h3> 
                </div> 
            ); 
    } 
} 
ReactDOM.render( 
    <DemoClassComponent username = "User"/>,  
    document.getElementById("root") 
);

output:

Class Component React
Class Component React

Example of Functional based Component props

In Functional Components, to access a prop from a function we do not need to use the ‘this’ keyword anymore. Functional components accept props as parameters and can be accessed directly.

Example:

index.html: Let’s suppose our index.html file has the following statement inside it:

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

index.js: Add this code in our index.js file.

import React from 'react';
import ReactDOM from 'react-dom';

function DemoFunctionalComponent(props){ 
    return( 
        <div> 
            {/*accessing information from props */} 
            <h2>Hello {props.username}</h2> 
            <h3>Welcome to TSinfo</h3> 
         </div> 
    ); 
} 
ReactDOM.render( 
    <DemoFunctionalComponent username = "User"/>,  
    document.getElementById("root") 
);

The output of this program will be the same as that of the above program. The only difference is that we have used a function-based component instead of the class-based component.

Passing information from one component to another

We will pass some information as props from our Parent component to the Child component. We can pass as many props as we want to a component.

Example:

index.html: Let’s suppose our index.html file has the following statement inside it:

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

index.js : Add this code in our file index.js file.

import React from 'react';
import ReactDOM from 'react-dom';

class Parent extends React.Component{ 
    render(){ 
        return( 
                <div> 
                    <h2>Parent Component props</h2>
                    <text>name="Bijay"  Address= "Bangalore"</text> 
                    <Child name="Bijay"  Address= "Bangalore"/> 
                </div> 
            ); 
    } 
} 
  
// Child Component 
class Child extends React.Component{ 
    render(){ 
        return( 
                <div> 
                    <h3>Accecss Parent Component props in Child Component</h3>
                    <div><text>User Name:{this.props.name}</text></div>                   
                    <div><text>Address: {this.props.Address}</text></div>
                     
                </div> 
            ); 
    } 
} 
ReactDOM.render( 
   // <DemoFunctionalComponent username = "User"/>, 
   <Parent/>, 
    document.getElementById("root") 
); 

output:

react passing component props to another component
react passing component props to another component

Note: Props are read-only. We are not allowed to modify the content of a prop. Whatever the type of Component is – functional or class-based, none of them is allowed to modify their props.

defaultProps in React JS

The defaultProps is a method which we can use to store as much information as we want for a particular class. And this information can be accessed from anywhere inside of that particular class.

Let’s look at an example where we will be using defaultProps to create some props for a class.

import React from 'react';
import ReactDOM from 'react-dom';

class ExampleofDefaultProps extends React.Component{ 
    render(){ 
        return( 
                <div> 
                    {/* using default prop - title */} 
                    <h2>Example of defaultprops</h2>
                    <div><b>Name of the company:</b> {this.props.CompanyName}</div>
                    <div><b>Locatioin:</b> {this.props.Location}</div>
                </div> 
            ); 
    } 
} 
  
// Creating default props for  
// ExampleClass Component 
ExampleofDefaultProps.defaultProps = { 
    CompanyName: "TSInfo",
    Location:"Bangalore"

} 
ReactDOM.render( 
   // <DemoFunctionalComponent username = "User"/>, 
   <ExampleofDefaultProps />, 
    document.getElementById("root") 
); 

output:

Reactdefaultprops
React defaultprops

propTypes in React js

We can use the propType for validating any data we are receiving from props. But before using it we will have to import it. Add the below line at the top of your index.js file :

import PropTypes from 'prop-types';

It is just like defaultProps, propTypes are also objects where keys are the prop names and values are their types. Below syntax shows how to use propTypes:

Syntax:

ComponentClassName.propTypes{   
    propName1 : PropTypes.number,
    propName2 : PropTypes.string,
    propName3 : PropTypes.bool,
    .
    .
    .
    propNamen : PropTypes.anyOtherType
}

For the props which do not validate to the type of data specified by propTypes, a warning on the console will occur.

Let us see below an example that uses propTypes for validation.

index.html: Let’s suppose our index.html file has the following statement inside it:

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

index.js: Add this code in our index.js file.

import React from 'react';
import ReactDOM from 'react-dom';
import PropTypes from 'prop-types';

class ExampleofpropTypes extends React.Component{ 
    render(){ 
        return( 
                <div> 
                    {/* using default prop - title */} 
                    <h2>Example of propTypes</h2>
                    <div><b>Name of the company:</b> {this.props.CompanyName}</div>
                    <div><b>Location:</b> {this.props.Location}</div>
                    <div><b>ContactNo:</b> {this.props.ContactNo}</div>
                </div> 
            ); 
    } 
} 

ExampleofpropTypes.propTypes = { 
     
    CompanyName: PropTypes.string, 
    Location: PropTypes.string, 
    ContactNo: PropTypes.number, 
} 
  
// Creating default props for  
// ExampleClass Component 
ExampleofpropTypes.defaultProps = { 
    CompanyName: "TSInfo",
    Location:"Bangalore",
    ContactNo:"1234567890"

} 
ReactDOM.render( 
   // <DemoFunctionalComponent username = "User"/>, 
   <ExampleofpropTypes />, 
    document.getElementById("root") 
); 

output:

ReactJs propTypes
ReactJs propTypes

You can see in the above example, that we are passing the prop named “ContactNo” as a string but validating it as a number. Still, everything is rendered perfectly on the browser but our browser console has a warning message. This message clearly tells us that the prop named ContactNo was expected to contain a numeric value but instead a string value is passed.

Note: React will check props passed to your components against those definitions, and warn in development if they don’t match. So, we will have to install that package separately in order to use it.

npm install --save prop-types

State in React Js

  • The State of a component is an object that holds some information that may change over the lifetime of the component.
  • The State is like a data store to the ReactJS component. It is mostly used to update the component when the user performed some action like clicking the button, typing some text, etc.
  • React.Component is the base class for all class based ReactJS components. Whenever a class inherits the class React.Component it’s constructor will automatically assign attribute state to the class with initial value is set to null. we can change it by overriding the method constructor.

Example:

index.html: Let’s suppose our index.html file has the following statement inside it:

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

index.js: Add this code in our index.js file.

import React from 'react';
import ReactDOM from 'react-dom';
class ExampleofState extends React.Component {
    constructor(props) {
      super(props);
      this.state = {name:"Bijay"};
    }
  
    render() {
      return (
        <div>
          <h1>Hello, world!</h1>
          <h2>I am {this.state.name}.</h2>
        </div>
      );
    }
  }
  
  ReactDOM.render(
    <ExampleofState />,
    document.getElementById('root')
  );
React State Examples
React State Examples

setState in React JS:

In many cases, we need to update the state. To do that we have to use the method setState.

Example:

index.html: Let’s suppose our index.html file has the following statement inside it:

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

index.js: add this code in our index.js file.

class ExampleofsetState extends React.Component {
    constructor(props) {
      super(props);
      this.state = {name:"Bijay"};
      
    }
    onClick = () => {this.setState({name:"Lakshmi"})}
    render() {
      return (
        <div>
          <h1>Hello, world!</h1>
          <h2>I am {this.state.name}.</h2>
          <button onClick={this.onClick} >Click-setState</button>
        </div>
        
      );
    }
  }
  
  
  ReactDOM.render(
    <ExampleofsetState />,
    document.getElementById('root')
  );

output:

React setState
React setState

When we click on button name called “Click-setState” then the name of the state (” this.state = {name:”Bijay”}; “) will be updated with name of the setState (” this.setState({name:”Lakshmi”}) “).

Reactjs setState
Reactjs setState

Difference between props and state in React js:

  • The state is mutable.
  • The state is referred to the local state of the component which cannot be accessed and modified outside of the component and only can be used & modified inside the component.
  • Component’s state is initialized inside a constructor and can be changed later using inbuilt setState() function.
  • Props are immutable(cannot be changed).
  • One of the most important features of props is that they can be passed by a parent component to its child components.
  • Props are owned by a parent component and are read-only.

React Js Component Life Cycle

React components have several “lifecycle methods” that allow us to execute actions at particular times.

There are four stages in the lifecycle of a component:

  • Initialization
  • Mounting
  • updating
  • unmounting

Initialization:

This is the stage where the component is constructed with the given Props and default state. This is done in the constructor of a Component Class.

Mount:

When React creates an instance of a component and inserts it into the DOM (mounting), the following methods are called:

  • constructor()
  • componentWillMount()
  • render()
  • componentDidMount()

Update:

If props or state of a component are changed for whatever reason, an update of the component is performed, the following methods are called.

  • componentWillReceiveProps()
  • shouldComponentUpdate()
  • componentWillUpdate()
  • render()
  • componentDidUpdate()

Unmount:

At some point our components will be removed from the DOM again, the following method is called.

  • componentWillUnmount.

React js Component Life-cycle Summary

Here’s a list of all life-cycle methods in the correct order.

  • getInitialState
  • componentWillMount
  • componentDidMount
  • componentWillReceiveProps
  • shouldComponentUpdate
  • componentWillUpdate
  • componentDidUpdate
  • componentWillUnmount

getInitialState():

The getInitialState() method is invoked first. It is invoked before React inserts a component into the DOM. If we want our component to have a state, then use this method to return the initial component’s state.

Syntax:

getInitialState: function(){
return { /* do something here */};
}

componentWillMount():

This method is called before rendering method, on both the server and the client side. Whenever React renders a component, it’s going to call componentWillMount first.

This method is only called once in the life of a component. This is the only lifecycle method that is called on the server side when you use serverside rendering.

syntax:

componentWillMount: function(){
/* Do something here */;
}

componentDidMount():

This method executed after the first render only on the client side. This is where AJAX requests and DOM or state updates should occur.

We can use this method to fetch data from a server with AJAX calls and also add event listeners inside componentDidMount.We are using it to update the state so we can trigger the other lifecycle methods.

This method is also used for any functions with delayed execution such as setTimeout or setInterval.

Syntax:

componentDidMount: function(){
/* Do something here */;
}

componentWillReceiveProps():

componentWillReceiveProps(nextProps)

Whenever a component receives a new set of props, this method will be called first. Also, note that React calls this method, even when the props have not changed. We triggered it from setNewNumber when we updated the state.

Syntax:

componentWillReceiveProps: function(newProps){
/* Do something here */;
}

shouldComponentUpdate():

shouldComponentUpdate(nextState, nextProps)

This method should return a true or false value. This will determine if the component will be updated or not. By default, it is set to true. It is Returning false means, that React will not execute componentWillUpdate(), render() and componentDidUpdate().

Syntax:

shouldComponentUpdate: function(nextProps, nextState){
// return a boolean value
return true;
}

componentWillUpdate():

This method is called right before rendering. It is called whenever new props are passed to the component, or the state is changed.

Syntax:

componentWillUpdate: function(nextProps, nextState){
// perform any preparations for an upcoming update
}

componentDidUpdate():

componentDidUpdate(prevProps, prevState)

This method is called just after rendering. componentWillUpdate gets called as soon as the the shouldComponentUpdate returned true.

Syntax:

componentDidUpdate: function(prevProps, prevState){
// perform any preparations for an upcoming update
}

componentWillUnmount():

This method is called Right before React unmounts and destroys our component.

Syntax:

componentWillUnMount: function(){
/* Do something here */;
}

New Life Cycle Methods Introduced in React:

Two new life-cycle methods are introduced very recently by the React team.

  • getDerivedStateFromProps() and
  • getSnapshotBeforeUpdate().

getDerivedStateFromProps():

This is one of the newer lifecycle methods introduced very recently by the React team. This will be a safer alternative to the method componentWillReceiveProps().

It is called just before calling the render() method.

getSnapshotBeforeUpdate():

getSnapshotBeforeUpdate() is another new lifecycle method introduced in React recently.

It is called just before the DOM is updated. The value that is returned from getSnapshotBeforeUpdate() is passed on to componentDidUpdate().

Basic Example of lifecycle methods:

index.html: Let’s suppose our index.html file has the following statement inside it:

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

App.js:

import React from 'react';
class App extends React.Component { 
  constructor(props) 
  { 
      super(props); 
      this.state = { hi : "World!" }; 
  } 
  componentWillMount() 
  { 
      console.log("componentWillMount():invoked before the component is mounted on the DOM"); 
  } 
  componentDidMount() 
  { 
      console.log("componentDidMount(): invoked after the component is mounted on the DOM"); 
  } 

  changeState() 
  { 
      this.setState({ hi : "User," }); 
  } 
  render() 
  { 
      return ( 
          <div> 
          <h2>Hi { this.state.hi }</h2> 
          <h3> 
           <button onClick={this.changeState.bind(this)}>click here!</button> 
          </h3> 
          </div>); 
  } 
  shouldComponentUpdate(nextProps, nextState) 
  { 
      console.log("shouldComponentUpdate()"); 
      return true; 
  } 
  componentWillUpdate() 
  { 
      console.log("componentWillUpdate():executed after the updation of State or Props"); 
  } 
  componentDidUpdate() 
  { 
      console.log("componentDidUpdate():executed after the updation of State or Props"); 
  } 
} 
export default App;

Index.js: Open index.js file and import App.js file here.

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
ReactDOM.render( 
    <App />, 
    document.getElementById('root')); 

output: before click on the button.

react component lifecycle methods
react component lifecycle methods

After click on the button, life-cycle methods updated on the console.

react lifecycle methods
react lifecycle methods

Import/Export in ReactJS

Importing:

In React we use the keyword import and from to import a particular module or a named parameter. Let us now see the different ways we can use the import operation to React.

Importing default export:

Every module is said to have at most one default export. In order to import the default export from a file fallow the below syntax.

Syntax:

import Given_Name from Address

Example: For example, we have two files one file name is called Button.js and second file name is called Main.js. Now see the below example how we can import Button.js file in Main.js file.

import Button from './Button'; // Import a component from another file

In the above example, Button is component importing from the Button.js file. If you observed here in the import operation, no need to mention “.js” extension for the file name called Button.js. We should call like ‘./filename’

Importing named values:

Every module can have several named parameters and in order to import one, we should follow the below syntax.

Syntax:

 import {param-name} from Address

Example:

import { Component } from './Button';

similarly, for multiple such imports, we can use a comma to separate two parameter name within the curly braces “{ }”.

Importing a combination of Default Exports and Named Values:

To import a combination, we should use the following syntax.

import Given_Name, { Para_Name, … } from Address

Example:

import React, { Component } from 'react';

Exporting:

In React we use the keyword export to export a particular module or a named parameter or a combination. Let’s see the different ways we can use the export operation to React.

Exporting default export:

Every module has at most one default export. To import the default export from a file, we need to follow the below syntax.

export default Given_Name

Example:

export default Button; // Don’t forget to use export default!

Exporting named values: Every module has several named parameters. To export one, we should follow the below syntax.

export { Para_Name }

similarly, for multiple such exports, we can use a comma to separate two parameter name within the curly braces “{ }”.

Let’s see in the example below where we would use the import and export operations in several ways. There we have three files, one indesx.html, index.js, and the third one App.js. Now we will see how to implement the import and export operations.

Example:

index.html: Let’s suppose our index.html file has the following statement inside it:

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

App.js:

import React from 'react';
class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {name:"Bijay"};
    
  }
  onClick = () => {this.setState({name:"Lakshmi"})}
  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>I am {this.state.name}.</h2>
        <button onClick={this.onClick} >Click-setState</button>
      </div>
      
    );
  }
}
// Exporting the component
export default App;

index.js:

//importing React module
import React from 'react';
import ReactDOM from 'react-dom';
//importing custom module
import App from './App';

ReactDOM.render(
    <App />,
    document.getElementById('root')
  );
React import/export Example
React import/export Example

refs in React:

refs are used to getting the reference to a DOM node or an instance of a component in a React Application i.e. refs would return the node we are referencing.

createRef in React

We can create a ref by calling “React.createRef()” and attaching a React element to it using the “ref” attribute on the element.

Example:

index.html: Let’s suppose our index.html file has the following statement inside it:

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

App.js:

import React from 'react';

class App extends React.Component {
  constructor(props) {
    super(props)
    //create the ref
    this.dateInput = React.createRef();
    this.state = {
      date: ''
    }
  }

handleInputDate = e => {
  e.preventDefault();//To prevent a browser reload/refresh
  this.setState({ date: this.dateInput.current.value})
};

render() {
  return (
    <div>
      <h1>Ref in React - createRef</h1>
      <h3>Value: {this.state.date}</h3>
      <form onSubmit={this.handleInputDate}>
      {/* call the ref with the 'ref' attribute */}
        <input type="date" ref={this.dateInput} />
        <button>Add</button>
      </form>
    </div>
  );
}
}
export default App;

Index.js:

import React from 'react';
import ReactDOM from 'react-dom';
//importing module
import App from './App';

ReactDOM.render(<App />, document.getElementById("root"));

output:

React createref example
React createref example

Select the date from date field and click on add button.

React ref example
React ref example

This is a component that renders text, an input field(date) and a button. The ref is created in the constructor and then attached to the input element when it renders.

When the button is clicked, the value submitted from the input element (which has the ref attached) is used to update the state of the text (contained in an h3 tag). We make use of this.dateInput.current.value to access the value and the new state is then rendered to the screen.

Passing a callback function to ref

React allows us to create a ref by passing a callback function to the ref attribute of a component.

Example:

Let’s see how that looks in the same example we used before.

App.js:

 class App extends React.Component {
  constructor(props) {
    super(props)
    //create the ref
    this.dateInput = React.createRef();
    this.state = {
      date: ''
    }
  }
handleInputDate = e => {
  e.preventDefault();//to prevent a browser reload/refresh
  this.setState({ date: this.dateInput.value})
};

render() {
  return (
    <div>
      <h1>Ref in React - createRef</h1>
      <h3>Date: {this.state.date}</h3>
      <form onSubmit={this.handleInputDate}>
      {/* call the ref with the 'ref' attribute */}
        {/* </form><input type="date" ref={this.dateInput} /> */}
        <input type="date" ref={e => this.dateInput = e}></input>
        <button>Add</button>
      </form>
    </div>
  );
}
}
export default App;

Forwarding a ref from one component to another

Ref forwarding is the technique of passing a ref from a component to a child component by making use of the React.forwardRef() method.

const Input = React.forwardRef((props, ref) => (
  <input type="date" ref={ref} /> 
));

Example:

Let’s see how that looks in the same example we used before.

App.js:

import React from 'react';

const Input = React.forwardRef((props, ref) => (
  <input type="date" ref={ref} />
  
));

class App extends React.Component {
    constructor(props) {
      super(props)
      this.inputDateRef = React.createRef();
      this.state = {
        date: ''
      }
    }
  
  handleInputDate = e => {
    e.preventDefault();
    this.setState({ date: this.inputDateRef.current.value})
  };

  render() {
    return (
      <div>
        <h1>Ref in React - forwardRef</h1>
        <h3>Date: {this.state.date}</h3>
        <form onSubmit={this.handleInputDate}>
          <Input ref={this.inputDateRef} />
          <button>Add</button>
        </form>
      </div>
    );
  }
}
export default App;

Using ref for form validation

We know that things like making sure a form cannot be submitted with an empty input value. So, in react, refs can come in handy for these types of validations. Let’s see in the below simple example how to do the validation using refs.

Example:

App.js: Add this code in out App.js file.

import React from 'react';

class App extends React.Component {
  constructor(props) {
    super(props);

    this.empName = React.createRef();
    this.company = React.createRef();
    this.contactNo = React.createRef();
    this.state = {
      errors: []
    };
  }

  handleSubmit = (event) => {
    event.preventDefault();
    const empName = this.empName.current.value;
    const company = this.company.current.value;
    const contactNo = this.contactNo.current.value;
    const errors = this.handleValidation(empName, company, contactNo);

    if (errors.length > 0) {
      this.setState({ errors });
      return;
    }
    // submit data
  };

  handleValidation = (empName, company, contactNo) => {
    const errors = [];
    if (empName.length === 0) {
      errors.push("Employee name cannot be empty");
    }
    if (company.length === 0) {
      errors.push("Company Name cannot be empty");
    }

    if (contactNo.length < 10 ) {
      errors.push("contact number not less than 10 digits");
    }

    return errors;
  };

  render() {
    const { errors } = this.state;
    return (
      <div>
        <h1>React Ref-Form Example</h1>
        <form onSubmit={this.handleSubmit}>
          {errors.map(error => <p key={error}>{error}</p>)}
          <div>
            <label>Employee Name:</label>
            <input type="text" ref={this.empName} />
          </div>
          <div>
            <label>Company Name:</label>
            <input type="text" ref={this.company} />
          </div>
          <div>
            <label>Contact Number:</label>
            <input type="number" ref={this.contactNo} />
          </div>
          <div>
            <button>Submit</button>
          </div>
        </form>
      </div>
    );
  }
}
export default App;

output:

React refs validations
React refs validations

Lists in React JS

We can create lists in React in a similar manner as we do in regular JavaScript. In React, from the component’s point of view, we can say that we will pass a list to a component using props and then use this component to render the list to the DOM. We will see how to do this to react.

Example:

index.html: Let’s suppose our index.html file has the following statement inside it:

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

App.js:

import React from 'react';

function NavmenuList(props) 
{ 
    const list = props.menuitems; 
  
    const updatedList = list.map((listItems)=>{ 
        return <li>{listItems}</li>; 
    }); 
  
    return( 
        <ol>{updatedList}</ol> 
    ); 
} 
export {NavmenuList} ;

Index.js:

import React from 'react';
import ReactDOM from 'react-dom';
import App,{NavmenuList} from './App';

const menuItems = ['Home','Contact Us','About Us','Trainig'];
ReactDOM.render( 
    <NavmenuList menuitems = {menuItems} />,  
    document.getElementById('root') 
); 

output:

React List
React List

Keys in React JS

Keys help React distinguish items in a list. It helps the React manage the changed items, new items added, or items removed from the list.

From an array of objects, you create a new array containing tags, which should have the key attribute, and their values are not allowed to be the same.

Example:

index.html: Let’s suppose our index.html file has the following statement inside it:

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

Index.css:

.product-list  {
  border:1px solid green;
  list-style-type : none;
  padding: 5px;
  margin: 5px;
  background-color: dodgerblue
}
.product {
   border: 1px solid skyblue;
   margin: 5px;
   padding: 5px;
   color: white
}
h2{
  color: white;
}

App.js:

import React from 'react';
import './index.css';
class Product extends React.Component {
  render() {
    return (
      
      <li className="product">
       
        <div>
          <b>Product Name:</b> {this.props.productName}
        </div>
        <div>
          <b>Owner:</b> {this.props.owner}
        </div>
      </li>
    );
  }
}
 
// productList Component
class ProductList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      products: [
        { productId: 1, productName: "Pears", owner: "Unilever" },
        { productId: 2, productName: "Colgate", owner: "Colgate-Palmolive" },
        
      ]
    };
  }
 
  render() {
    // Array of <Products>
    var productlistItems = this.state.products.map(e => (
      <Product key={e.productId} productName={e.productName} owner={e.owner} />
    ));
    return (
      
        <ul className="product-list">
        <h2>Product Details</h2>
           {productlistItems}
        </ul>
      );
  }
}
export {ProductList};

Index.js:

import React from 'react';
import ReactDOM from 'react-dom';
import App,{ProductList} from './App'
ReactDOM.render(<ProductList />, document.getElementById("root"));

output:

react keys
react keys

Routes in React JS

React router is a routing library built on top of the react which is used to create the routing in react apps.

To install the react router you need to download the react-router-dom package by running the following commands.

npm install react-router-dom

Example:

index.html: Let’s suppose our index.html file has the following statement inside it:

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

Index.css:

h2{
  color: white;
} 
.RouterExample{
  background-color: dodgerblue
}
.routerexample{
  background-color: gray
}

App.js:

React router gives us components like [Route,Link,BrowserRouter] which help us to implement the routing.

Import index.css file in App.js file.

import react from "react";
import { BrowserRouter as Router, Route, Link } from "react-router-dom";
import './index.css';
function RouterExample() {
  return (
    <Router>
      <div class="Router Example">
        <h2>TS Info Technologies</h2>
        <ul>
          <li>
            <Link to="/">Home</Link>
          </li>
          <li>
            <Link to="/about">About</Link>
          </li>
          <li>
            <Link to="/training">Training</Link>
          </li>
          <li>
            <Link to="/career">Career</Link>
          </li>
        </ul>
         </div>
        <hr />
        <div class='routerexample'>
       <Route exact path="/" component={Home} />
        <Route path="/about" component={About} />
        <Route path="/training" component={Training} />
        <Route path="/career" component={Career} />
      </div>
    </Router>
  );
}

function Home() {
  return (
    <div>
      <h2>Home</h2>
    </div>
  );
}

function About() {
  return (
    <div>
      <h2>About</h2>
    </div>
  );
}

function Training({ match }) {
  return (
    <div>
      <h2>Training</h2>
      <ul>
        <li>
          <Link to={`${match.url}/SharePoint Onpremise`}>SharePoint Onpremise</Link>
        </li>
        <li>
          <Link to={`${match.url}/Office 365`}>Office 365</Link>
        </li>
        <li>
          <Link to={`${match.url}/Nintex Workflow`}>Nintex Workflow</Link>
        </li>
      </ul>

      <Route path={`${match.path}/:courseId`} component={Trainings} />
      <Route
        exact
        path={match.path}
        render={() => <h3>Please select a course.</h3>}
      />
    </div>
  );
}

function Trainings({ match }) {
  return (
    <div>
      <h3>{match.params.courseId}</h3>
    </div>
  );
}
function Career() {
  return (
    <div>
      <h2>Career</h2>
    </div>
  );
}

export default RouterExample;

Index.js: open the index.js file and import the component “App“.

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
ReactDOM.render(
    <App />,
 document.getElementById('root'));

output:

react routers
react routers

Flux in React JS

Flux is a pattern for managing how data flows through a React application. It is a programming concept, where the data is uni-directional.

Four logical entities in flux, they are:

  • Actions
  • Dispatcher
  • Stores
  • Views

Actions: Actions are objects that we create when our application’s state changes. These actions are sent to the Dispatcher to trigger the data flow.

Dispatcher:The dispatcher is responsible for dispatching all the actions to all stores.

  • It stores register with a dispatcher. They provide a callback function.
  • All actions are dispatched by a dispatcher to all the stores that are registered with it.

Stores: Stores are responsible for managing your application’s data. They provide methods for accessing that data, but not for changing it. If you want to change data in stores, you have to create and dispatch an action.

Views: The view will receive data from the store and re-render the app.

The idea behind Flux is that there is a single source of truth (the stores) and they can only be updated by triggering actions. The actions are responsible for calling the dispatcher, which the stores can subscribe for changes and update their own data accordingly.

When a dispatch has been triggered, and the store updates, it will emit a change event which the views can rerender accordingly.

Flux architecture is:

Actions->Dispatcher->Stores->Views

To install Flux, follow the below command.

npm install --save flux

Redux in React:

Unlike Flux, Redux does not use a dispatcher, but instead it uses pure functions to define data mutating functions. It still uses stores and actions, which can be tied directly to React components.

Three major principles of Redux:

  • Updates are made with pure functions (in reducers)
  • The state is a read-only property
  • The state is the single source of truth (there is only one store in a Redux app)

One big difference with Redux and Flux is the concept of middleware. Redux added the idea of middleware that we can use to manipulate actions as we receive them, both coming in and heading out of our application.

To install Redux, use the below command.

npm install --save react-redux

You may like following js tutorials:

I hope this react js tutorial helps to learn react js step by step with various examples.

We also learn, react js tutorial concepts like what is react js? how does react js works? advantages of react js, react js components, import/export in react js, refs in react js, lists in react js, keys in react js, routes in react js, flux in react js etc.

>