React Js Tutorial

With the rapid improvements in the technologies and advancements in the real-time world, we see that there is a high demand for web applications as well. There is also a high increase in the development of web applications. Most of the organizations are involved in developing web applications based on the client requirements as per the agreed guidelines. To build web applications, we need to choose the right platforms with the right specifications that would suffice the need in the IT industry, meeting the client expectations along with a positive customer experience. React is one of the platforms that is used by most organizations in the current era of living along with the React js library. In this article, you will gain an understanding of what React js is, its features, working, react forms, state, and prop, along with the advantages and disadvantages, etc.

What is React Js

React Js is an efficient, flexible, and declarative Java library platform that has the primary focus on building reusable UI components. React Js is referred to as a component-based library that is applicable only for a single layer of application which is the view layer. It is an open-source front-end library that was initially developed on Facebook. And later on, it is used by other companies and organizations.
React JS is the library that helps in presenting the data that changes over time. Most of the people use react as the V in MVC. React is responsible for abstracting away the DOM from you and also is offering the better performance with the better programming model. React make use of the one-way reactive data flow implementation, which also helps in becoming easier rather than traditional data binding.

To gain in-depth knowledge with practical experience in React Js, Then explore HKR's React JS Training

Features of React JS

Below are the set of features in react JS which you need to be aware of: 


1. JSX: Jsx is referred to as an extension of javascript. You need to know that it is not mandatory to use  JSX in react. However, JSX is one of the important features and easy to use. 
2. Components: Components in react JS refer to the JavaScript functions that help in making the code easier. The code is made easier by splitting the logic in two different reusable independent codes. Components are used as functions and classes as well. Components also correspond to having  props, state which help in making life easier. The state of each of the props is maintained inside the class. 
3. Virtual DOM: React JS also creates a virtual DOM which is one of the important features. Virtual DOM is referred to as the in-memory data structure cache. Only the final changes of the DOM will be later updated in the browser DOM. 
4. JavaScript Expressions:JavaScript expressions utilised in the jsx files by using the curly brackets, {}.

React Js environment setup

To set up a successful development environment, there are many steps involved which will help in speeding up the development process. NodeJs is required, if you don’t have it installed, you can check the link below.
NodeJs and NPM: NodeJs is a platform that is needed for the ReactJs development. After successful installation of NodeJs, you can start installing React.

React Js can be installed in two different ways.

  1. Using Webpack and babel.
  2. Using the create-react-app command.

Installation of React Js using webpack and babel

Webpack is referred to as a module bundler that is responsible for managing and loading the independent modules. It will take all the dependent modules and compile the same to a single bundle. This bundle can be used while developing the applications using the command line or by configuring it using the webpack.config file.

Babel is a JavaScript compiler and transpiler which is used to convert one source code to another.

Below are the steps to be followed to install React js:

Step-1: Create the root folder:

You will need to create a folder with the name reactApp1 on your computer to perform the installation of all the files using mkdir command.

C:\Users\username\Desktop>mkdir reactApp

C:\Users\username\Desktop>cd reactApp

In order to create a module, you need to generate the file called package.json file. Once the folder is created, you can create a package called package.json file . To perform the same, you will need to run the npm init command from the command prompt.

C:\Users\username\Desktop\reactApp>npm init

This command further asks for more information about the module such as description, package name, author, etc.

Step-2: Install React and react dom

As our primary task is to install the React Js, install it and dom packages, using the install-react and react-dom command. You are also allowed to add the packages that we install to the package.json file using the save option.

C:\Users\Tutorialspoint\Desktop\reactApp>npm install react --save

C:\Users\Tutorialspoint\Desktop\reactApp>npm install react-dom --save

You can also install using a single command as

C:\Users\username\Desktop\reactApp>npm install react react-dom --save

Step-3: Install webpack


As we are utilizing the webpack to generate the bundler, we need to install webpack,  webpack-dev-server and webpack-cli.

C:\Users\username\Desktop\reactApp>npm install webpack --save

C:\Users\username\Desktop\reactApp>npm install webpack-dev-server --save

C:\Users\username\Desktop\reactApp>npm install webpack-cli --save

Also you can use a single command to install webpack:

C:\Users\username\Desktop\reactApp>npm install webpack webpack-dev-server webpack-cli --save

Step-4: Install Babel

You will need to install Babel, its plugins that include babel-loader, babel-preset-env, babel-preset-react and, html-webpack-plugin.

C:\Users\username\Desktop\reactApp>npm install babel-core --save-dev
C:\Users\username\Desktop\reactApp>npm install babel-loader --save-dev
C:\Users\username\Desktop\reactApp>npm install babel-preset-env --save-dev
C:\Users\username\Desktop\reactApp>npm install babel-preset-react --save-dev
C:\Users\username\Desktop\reactApp>npm install html-webpack-plugin --save-dev

They can be installed using a single command:

C:\Users\username\Desktop\reactApp>npm install babel-core babel-loader babel-preset-env
babel-preset-react html-webpack-plugin --save-dev

Step-5: Create the files

You will need to create the files and name them as you wish. You can create the files manually or using the command prompt.

Step-6: Set compiler, loader and servers

You will need to Open webpack-config.js file and add the required code. We are setting the webpack entry point to be main.js. Output path is the place where bundled apps will be served. We are also setting the development server to 8001 port. You can choose any port you want.

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
entry: './main.js',
output: {
path: path.join(__dirname, '/bundle'),
filename: 'index_bundle1.js'
},
devServer: {
inline: true,
port: 8001
},
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['es2015', 'react']
}
}
]
},
plugins:[
new HtmlWebpackPlugin({
template: './index.html'
})
]
}

Step-7: index.html

Index.html would be the regular HTML. Here, we need to set up div id = “app” as the root element  for the app.



   

      

      React App

      

      


      

   

Step-8: App.jsx and main.js

This will be the first react component.

App.jsx
import React, { Component } from 'react';
class App extends Component{
render(){
return(

Hello World


);
}
}

export default App;

Main.js

import React from 'react';

import ReactDOM from 'react-dom';

import App from './App.js';

ReactDOM.render(, document.getElementById('app'));

Step-9: Running the server

The setup will be complete and you need to start the server by running the following command.

C:\Users\username\Desktop\reactApp>npm start

Step-10: Generating the bundle

You will need to run the build command in the command prompt as represented below:

C:\Users\Tutorialspoint\Desktop\reactApp>npm run build

React JS Training

  • Master Your Craft
  • Lifetime LMS & Faculty Access
  • 24/7 online expert support
  • Real-world & Project Based Learning

React JS component Lifecycle

There are different life cycle methods in the component lifecycle in react JS. Let us know about them.

1. componentWillMount is used for execution before rendering, on both the client and server-side.
2. componentDidMount is executed only after the first render is completed on the client-side. This is where AJAX requests and DOM or state updates should occur. This method is specifically used for the integration of any functions with delayed execution such as setTimeout or setInterval and with other JavaScript frameworks. This method is used to update the state so that we can trigger the other lifecycle methods.
3. componentWillReceiveProps is invoked once the props are updated before calling another render. It is triggered from setNewNumber when the state is updated.
4.shouldComponentUpdate should return a true or false value. This will help in determining if the component will be updated or not. By default, the value is set to true. The false value can be returned if you are sure that the component doesn't need to render after the state or props are updated.
5.componentWillUpdate is called just before rendering.
6.componentDidUpdate is called just after rendering.
7.componentWillUnmount is called after the component is unmounted from the dom. We are unmounting our component in main.js

Below is the example of the code used to show the two methods called at each state.

Example: Cofile.jsx

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

class CO_LIFE extends React.Component {

  constructor(props) {

    super(props);

    this.state = {Name1: ''};


    this.UpdateName = this.UpdateName.bind(this);

    this.testclick = this.testclick.bind(this);

  }

  UpdateName(event) {

    this.setState({name: event.target.value});

  }

  testclick(event) {

    alert("The entered name is : "+ this.state.name);

  }

   componentDidMount() {  

    console.log('Mounting State : calling method componentDidMount');

  }   

  shouldComponentUpdate() {  

    console.log('Update  State : calling method shouldComponentUpdate');

    return true;

  }  

  componentDidUpdate() {  

    console.log('Update  State : calling method componentDidUpdate')  

  }  

  componentWillUnmount() {  
    console.log('UnMounting State : calling method componentWillUnmount');

  }  

  render() {

    return (

      
        

         Enter the Name:
        

        

{this.state.name}



        

      


    );

  }

}

export default CO_LIFE;

Index.jsx:

import React from 'react';

import ReactDOM from 'react-dom';

import COMP_LIFE from './complife.jsx';

ReactDOM.render(

    ,

    document.getElementById('root')

); 

Let me give a brief review about components, combining the components to make the application easier to maintain. That will help in updating and changing the components without modifying or affecting the rest of the page. 
Stateless example: The first component that we are using in the example is NewApp. The componentt is the owner of the Header1 and Content1. Hence we will be creating Header1 and Content1 separately by just adding it inside our JSX tree in the NewApp component.

NewApp.jsx:

import React from 'react';

class NewApp extends React.Component {

   render() {

      return (

         


            


            

         


      );

   }

}

class Header1 extends React.Component {

   render() {

      return (

         


            

Header



         


      );

   }

}

class Content1 extends React.Component {

   render() {

      return (

         


            

Content



           

The content text!!!



         

      );

   }

}

export default App;
In order to render the same thing on the page, you will need to import the main.js file and also call the function reactDOM.render().

Main.js file: 

import React from 'react';

import ReactDOM from 'react-dom';

import App from './App.jsx';

ReactDOM.render(, document.getElementById('NewApp'));

Stateful Example: In the below example, you will need to set up the state for the owner component (NewApp). The header component will be added in the same way as in the previous example. However, in the stateful example, we will be creating the table and tbody elements  instead of the content tag. Here, you will see a dynamic insertion of TableRow for every object from the data array.


Below is the set of the code to be used.

import React from 'react';
class NewApp extends React.Component {

   constructor() {

      super();

      this.state = {

         data: 

         [

            {

               "id1":1,

               "name1":"Foo",

               "age1":"20"

            },

            {

               "id1":2,

               "name1":"Bar",

               "age1":"30"

            },

            {

               "id1":3,

               "name1":"Baz",

               "age1":"40"

            }

         ]

      }

   }

   render() {

      return (

         


            


                                             {this.state.data.map((person, i) =>                      data = {person} />)}                           


         


      );

   }

}

class Header extends React.Component {

   render() {

      return (

         


            

Header



         


      );

   }

}

class TableRow extends React.Component {

   render() {

      return (

                     {this.props.data.id1}            {this.props.data.name1}            {this.props.data.age1}         

      );

   }

}

export default App;

import React from 'react';

import ReactDOM from 'react-dom';

import App from './App.jsx';

ReactDOM.render(, document.getElementById('app'));

State in React Js

A state is referred to as a place where the data is coming from. It is important for us to ensure that the state is simple and easier, minimizing the number of stateful components.  Let us consider that we have ten components that require the data from the state. We will need to create a container that will help in holding and keeping the state for all the ten components.


Using State: Below is the set of the sample code that will show us on how to create a stateful component.

NewApp.jsx:

import React from 'react';

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

this.state = {
header: "Header from state...",
content: "Content from state..."
}
}
render() {
return (

{this.state.header}


{this.state.content}


);
}
}

export default App;

Main.jsx:

import React from 'react';

import ReactDOM from 'react-dom';

import App from './App.jsx';

ReactDOM.render(, document.getElementById('app'));

Props in react JS

The difference between props and state is that the props are immutable. Hence, it is required for the container component to be defined with the state that has to be updated or changed. The child components are required to pass the data from the state using the props.

Usage of Props:

Whenever we need immutable data in our component, we can just add the props to the function called reactDOM.render() in main.js and we can use the same inside our component.

import React from 'react';


class NewApp extends React.Component {

   render() {

      return (

         


            

{this.props.headerProp}



            

{this.props.contentProp}



         


      );

   }

}

export default App;

main.jsx: 

import React from 'react';

import ReactDOM from 'react-dom';

import App from './NewApp.jsx';

ReactDOM.render(
   from props..."/>, document.getElementById('Newapp'));

Default props: Default props will help you in allowing to set a default Property value directly on the component constructor rather than adding that to the reactDom.render() element.

import React from 'react';

class NewApp extends React.Component {

   render() {

      return (

         


            

{this.props.headerProp}



            

{this.props.contentProp}



         


      );

   }

}

App.defaultProps = {

   headerProp: "Header from props...",

   contentProp:"Content from props..."

}

export default NewApp;

Combination of state and props: Below is the example that will help you in presenting the combination of state and props in your app. In this combination, we will set up the state in a parent component and pass the same to the component tree by using the props in the render function, the headerProp1 and contentProp1 used in the child components.

import React from 'react';


class NewApp extends React.Component {

   constructor(props) {

      super(props);

      this.state = {

         header: "Header from props...",

         content: "Content from props..."

      }

   }

   render() {

      return (

         


            


            

         


      );

   }

}

class Header extends React.Component {

   render() {

      return (

         


            

{this.props.headerProp1}



         


      );

   }

}

class Content extends React.Component {

   render() {

      return (

         


            

{this.props.contentProp1}



         


      );

   }

}

Subscribe to our youtube channel to get new updates..!

React Js Forms

In React Js, the HTML elements like ,

Find our upcoming React JS Training Online Classes

  • Batch starts on 29th Sep 2022, Weekday batch

  • Batch starts on 3rd Oct 2022, Weekday batch

  • Batch starts on 7th Oct 2022, Fast Track batch

Global Promotional Image
 

Categories

Request for more information

Amani
Amani
Research Analyst
As a content writer at HKR trainings, I deliver content on various technologies. I hold my graduation degree in Information technology. I am passionate about helping people understand technology-related content through my easily digestible content. My writings include Data Science, Machine Learning, Artificial Intelligence, Python, Salesforce, Servicenow and etc.