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.

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 the successful installation of NodeJs, you can start installing React. React Js can be installed in two different ways.

  • Using Webpack and babel.
  • 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.
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "UTF-8">
<title>React App</title>
</head>
<body>
<div id = "app"></div>
<script src = 'index_bundle.js'></script>
</body>
</html>

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(
<div>
<h1>Hello World</h1>
</div>
);
}
}
export default App;

Main.js

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

ReactDOM.render(<App />, 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 (
<div>
Enter the Name:<input type="text" value={this.state.name} onChange={this.UpdateName} /><br/>
<h2>{this.state.name}</h2>
<input type="button" value="Click Here" onClick={this.testclick} />
</div>
);
}
}

export default CO_LIFE;

Index.jsx:

import React from 'react';
import ReactDOM from 'react-dom';
import COMP_LIFE from './complife.jsx';

ReactDOM.render(
<COMP_LIFE />,
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 component 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 (
<div>
<Header/>
<Content/>
</div>
);
}
}
class Header1 extends React.Component {
render() {
return (
<div>
<h1>Header</h1>
</div>
);
}
}
class Content1 extends React.Component {
render() {
return (
<div>
<h2>Content</h2>
<p>The content text!!!</p>
</div>
);
}
}
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(<App />, 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 (
<div>
<Header/>
<table>
<tbody>
{this.state.data.map((person, i) => <TableRow key = {i}
data = {person} />)}
</tbody>
</table>
</div>
);
}
}
class Header extends React.Component {
render() {
return (
<div>
<h1>Header</h1>
</div>
);
}
}
class TableRow extends React.Component {
render() {
return (
<tr>
<td>{this.props.data.id1}</td>
<td>{this.props.data.name1}</td>
<td>{this.props.data.age1}</td>
</tr>
);
}
}
export default App;

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

ReactDOM.render(<App/>, document.getElementById('app'));

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

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 (
<div>
<h1>{this.state.header}</h1>
<h2>{this.state.content}</h2>
</div>
);
}
}
export default App;

Main.jsx:

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

ReactDOM.render(<App />, 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 (
<div>
<h1>{this.props.headerProp}</h1>
<h2>{this.props.contentProp}</h2>
</div>
);
}
}
export default App;

main.jsx:

import React from 'react';
import ReactDOM from 'react-dom';
import App from './NewApp.jsx';

ReactDOM.render(<NewApp headerProp = "Header from props..." contentProp = "Content
from props..."/>, document.getElementById('Newapp'));

export default App;

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 (
<div>
<h1>{this.props.headerProp}</h1>
<h2>{this.props.contentProp}</h2>
</div>
);
}
}
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 (
<div>
<Header headerProp1 = {this.state.header}/>
<Content contentProp1 = {this.state.content}/>
</div>
);
}
}
class Header extends React.Component {
render() {
return (
<div>
<h1>{this.props.headerProp1}</h1>
</div>
);
}
}
class Content extends React.Component {
render() {
return (
<div>
<h2>{this.props.contentProp1}</h2>
</div>
);
}
}
export default NewApp;

React Js Forms:

In React Js, the HTML elements like <input/>, <textarea/> and <select/> will have their own state and will have to be updated as and when the user interacts using the method called setState() method.

Working with Forms in React Js:

import React from 'react';
import ReactDOM from 'react-dom';
class Form extends React.Component {
constructor(props) {
super(props);
this.state = {Name: ''};

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

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

formSubmit(event) {
alert("The name entered is: "+ this.state.name);
}

render() {
return (
<form>
Enter the Name:<input type="text" value={this.state.name} onChange={this.UpdateName} /><br/>
<h2>{this.state.name}</h2>
<input type="submit" value="Submit" onClick={this.formSubmit} />
</form>
);
}
}

export default Form;

We need to maintain the state, so that react will provide a special method called setState which helps in maintaining the state whenever there is a change.

The events called onChange and onClick on the text box and submit button. Whenever the user enters the text inside the textbox, the event onChange is called and the name field state object state will be updated as represented below:

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

Index.js

import React from 'react';
import ReactDOM from 'react-dom';
import Form from './form.jsx';

ReactDOM.render(
<Form />,
document.getElementById('root')
);

React JS Training

Weekday / Weekend Batches

Advantages of React Js:

  • React Js is using the virtual DOM that uses the in-memory data structure, final changes will be updated in the browser DOM which makes the app faster.
  • It helps in creating the components based on your choice by using the react component feature. The components can be reused and helpful in the code maintenance.
  • React Js has become very popular in a short span of time and is well maintained by instagram and Facebook.
  • React Js is mainly used to develop rich UI for both mobile and desktop applications.
  • React Js is easy to start as it is an open-source javascript library.
  • React Js is easy to test and debug as most of the coding is done in javascript rather than HTML.

Disadvantages of React Js:

  • The file size of React Js is large.
  • The coding is written in JSX, which includes both HTML and CSS as they are part of Javascript. It seems to be confusing as most of the frameworks would need HTML to be separated from the Javascript code.

Conclusion:

Technology is changing rapidly with a wide need of increase in the applications as per the customer requirements. Using the different platforms and libraries, most of the organizations are utilizing and meeting the timelines and requirements efficiently. React Js is one platform that is gaining its significance in the IT industry with its features and benefits. Many of the organizations are looking forward to individuals who have expertise in working in multiple projects related to React Js, building desktop and mobile applications. I would recommend you to get trained and certified in React for better opportunities and build your career with an exponential growth.

Find our upcoming React JS Training Online Classes

  • Batch starts on 28th Oct 2021, Weekday batch

  • Batch starts on 1st Nov 2021, Weekday batch

  • Batch starts on 5th Nov 2021, Fast Track batch

Global Promotional Image
 

Categories

Request for more information

Webinar

Python tutorial for beginners

5th April | 08:00 AM

150 Registered

Kavya Gowda
Kavya Gowda
Research Analyst
Kavya works for HKR Trainings institute as a technical writer with diverse experience in many kinds of technology-related content development. She holds a graduate education in the Computer science and Engineering stream. She has cultivated strong technical skills from reading tech blogs and also doing a lot of research related to content. She manages to write great content in many fields like Programming & Frameworks, Enterprise Integration, Web Development, SAP, and Business Process Management (BPM). Connect her on LinkedIn and Twitter.