[go: up one dir, main page]

0% found this document useful (0 votes)
47 views33 pages

Unit - 4

Full stack Unit 4 notes
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
47 views33 pages

Unit - 4

Full stack Unit 4 notes
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 33

UNIT IV - ADVANCED CLIENT SIDE PROGRAMMING

React JS: ReactDOM - JSX - Components - Properties – Fetch API - State and Lifecycle - -
JSLocalstorage - Events - Lifting State Up - Composition and Inheritance

Introduction to React:

React is “a JavaScript library for building user interfaces” developed by Facebook (though it is
released as open-source software). At its core, React allows you to dynamically generate and interact
with the DOM, similar to what you might do with jQuery. However, React was created to make it much
easier to define and manipulate lots of different parts of the DOM, and to do so quicklyof computer
speed). It does this by enabling you to declare a web app in terms of different components (think:
“things” or “parts” of a web page) that can be independently managed—this lets you design and
implement web apps at a higher level of abstraction. Moreover, components are usually associated with
some set of data, and React will automatically “re-render” (show) the updated component when the data
changes—and to do so in a computationally efficient manner.

React is currently the most popular “framework” for building large-scale web applications (its chief
competitors being Angular and Vue.js, though there are scores of similar frameworks that are also
used. Check out TodoMVC for an example of the same application in each!). This means that React is
generally very well documented; there are hundreds of tutorials, videos, and examples for building
React applications (of which this chapter will be yet another). Some general resources are included at
the end of the chapter, but in general we recommend you start with the official documentation,
particularly the set of main concepts. Note that this book more or less follows the approach used by
Facebooks’s Intro to React Tutorial.

React has gone through a number of different major versions in its short life. What’s more: the “style”
in which React is written has also evolved over time as new features are added to both the React library
and the JavaScript language. This book introduces and emphasizes an approach that prioritizes clarity
of concepts and readability of code, rather than conciseness of syntax or use of advanced options, while
also attempting to reflect the current practices in React development.

React is developed and maintained by Facebook (Meta). Facebook as a company has a long history
of violating the Fair Housing Act, leaking or selling personal private data, allowing the spread of
misinformation, enabling genocide and in general choosing profits over safety. You may be
understandably concerned about whether learning and using React implicitly supports and thus
condones this company and its behavior. Whenever you adopt any software tool or library, it is worth
investigating who created it (and why) and how that may impact your own willingness to use it as a
dependency.

Getting Set Up: Create React App

React is a JavaScript library similar to those discussed in previous chapters—you load the library and
then can call upon its methods. However, React makes use of a significant amount of advanced and
custom JavaScript syntax (described below), including extensive use of ES6 Modules. Thus in practice,
developing React apps requires using a large number of different development tools—just getting
setup and started is one of the major hurdles in learning React!

Luckily, Facebook does provide an amazing application which combines many of these these
different development tools together. Create React App (CRA) is a command line application that
generates scaffolding (“starter code”) for a React application, as well as provides built-in scripts to
run, test, and deploy your code.

You can use Create React App to create a new React app by running the program and specifying a name
for the folder you want the app to be created inside of. For example, the below command will create a
new folder called my-app that contains all of the code and tools necessary to create a React app:
# Create a new React app project in a new `my-app`
directory # This may take a minute...
npx create-react-app my-app --use-npm

# Change into new project directory to run further commands


cd my-app

The npx command is installed alongside npm 5.2.0 and later, and can be used to (temporarily)install and
run a global command in a single step. So rather than needing to use npm install -g create-react-app,
you can just use npx.
● If you specify the current directory (.) as the target folder name, Create React App will create a
new react app in the current folder! This is useful when you want to create a React app inside an
existing cloned GitHub repository.
● The --use-npm argument is optional, but will make sure that your app uses npm to manage
packages and not an alternate manager (such as yarn).

Running the Development Server

After you create a React app, you can use one of CRA’s provided scripts (the start script) to
automatically start up a development webserver:
# Make sure you are in the project directory
cd path/to/project

# Run the development server script


npm start

This will launch the webserver, and open up a new browser window showing the rendered web page!
This development webserver will automatically perform the following whenever you change the
source code:

1. It will transpile React code into pure JavaScript that can be run in the web browser
(see JSX below).

2. It will combine (bundle) all of the different code modules into a single file, and automatically
inject that single file into the HTML (adding the <script> tag for you).
3. It will display errors and warnings in your browser window—most errors will show up in the
developer console, while fatal errors (e.g., syntax errors that crash the whole app) will be shown as an
error web page. Note that the Chrome React Developer Tools will provide further error and debugging
options.

4. It will automatically reload the page whenever you change the source code! (Though it is often
good to manually refresh things when testing, just to make sure).

All these capabilities are provided by a tool called webpack. Webpack is at its core a module bundler: it
takes your complicated source code structure (lots of files) and transforms it into a brand new,
“simplified” version (a single file). In the process, can automatically process and change that code—
from automatic formatting and styling, to compiling or transpiling from one language to another.
Webpack is a fairly complex build tool in its own right; however, Create React App provides its
own configuration to this program so that you don’t have to do anything with it directly!

Project Structure

A newly created React app will contain a number of different files, including the following:
● The public/index.html file is the home page for your application when webpack builds the app. If
you look at this file, you’ll notice that it doesn’t include any CSS <link> or
JavaScript <script> elements—the CSS and JavaScript for your React app will be automatically
injected into the HTML file when the app is built and run through the development server. The CSS
and JavaScript files will be found in the src/ folder. Similarly, all of the content of the page will be
defined as JavaScript components—you’ll be creating the entire page in JavaScript files. Thus in
practice, you rarely modify the index.html file (beyond changing the metadata such as the <title> and
favicon).
Notice that the index.html file contains almost no HTML content— just the <head>, the <body> and a
single <div id="root">. That is because your entire app will be defined using React JavaScrip code; this
content will then be injected into the #root element.
Overall the public/ folder is where you put assets that you want to be available to your page but aren’t
loaded and compiled through the JavaScript (i.e., they’re not “source code”). For example, this is where
you would put an img/ folder to hold pictures to show. The public/ folder will be the “root” of the
webpage; a file found at public/img/picture.jpg would be referenced in your DOM as img/picture.jpg—
using a path relative to the public/ folder. See Using the public folder for details.
● The src/ folder contains the source code for your React app. The app is started by
the index.js script, but this script imports and uses other JavaScript modules (such as the
provided App.js script, which defines the “App” module). In general, you’ll code React apps by
implementing components in one or more modules (e.g., App.js, AboutPage.js), which will then
be imported and used by the index.js file. See the Components section below for details.
o The reportWebVitals.js and setupTests.js are provided by default to better support testing and
performance measurements. This text doesn’t cover these features; you can ignore or delete them
for now.
● The src/index.css and src/App.css are both CSS files used to style the entire page and the
individual “App” component respectively. Notice that the CSS files are imported from inside the
JavaScript files (with e.g., import './index.css' in the src/index.js file). This is because the webpack
build system that Create React App uses to run apps knows how to load CSS files, so you can “include”
them through the JavaScript rather than needing to link them in the HTML.
If you want to load an external stylesheet, such as Bootstrap or Font-Awesome, you can still do that by
modifying the public/index.html file—but it’s better to install them as modules and import them
through the JavaScript. See the documentation for Adding Bootstrap for an example.

o Remember that all CSS is global—rules specified in any .css file will apply to the entire app (i.e.,
the App.css rules will also apply to components other than those in App.js). The CSS is broken into
multiple files to try and keep rules organized. You can instead put all your CSS rules into a single
file,
using naming schema or other techniques to keep them organized. If you are interested in ways to keep
the CSS from being applied globally, look into using CSS in JS.
● The README.md contains a copy of the User Guide (which can also be found online),
focused on “how to perform common tasks”. the user guide is very thorough—if you want to do
something within the CRA framework, try searching this first, as there is probably a guide and example
code for you to use!
Overall, you’ll primarily be working with the .js and .css files found in the src/ folder as you develop a
React app.

Dom in React:

Real/Browser DOM:

DOM stands for 'Document Object Model'. It is a structured representation of HTML in the webpage
or application. It represents the entire UI(User Interface) of the web application as the tree data
structure.
It is a structural representation of HTML elements of a web application in simple words.
Whenever there is any change in the state of the application UI, DOM is updated and represents the
change. The DOM is rendered and manipulated with every change for updating the application
User Interface, which affects the performance and slows it down.
Therefore, with many UI components and the complex structure of DOM, It will update in
more expensive as it needs to be re-rendered with each change.
The DOM is constituted as a tree data structure. It consists of the node for each UI element present in
the web document.

Updating the DOM:

If we know some about JavaScript you may see people using


the 'getElementById()' or 'getElementByClass()' method to modify the contents of DOM.
Whenever there is any change that occurs in the state of your application, the DOM is updated to reflect
the change in the UI.

How Virtual DOM speeds things up:

When any new things are added to the application, the virtual DOM is created, represented as a tree.
Every element in the application is a node in the tree.
Therefore, whenever there is a change in the position of an element, a new virtual DOM is created. The
newer virtual DOM tree is compared with the latest, where the changes are noted.
It finds the possible way to make these changes by the actual DOM. Then the updated elements
would re-render on the page.

How Virtual DOM Helps in React:

Everything in React is observed as a component, a functional component, and a class component. A


component has a state. Whenever we change something in the JSX file, to put it simply, whenever
the state of the component is changed, the react updates its virtual DOM tree.
React maintains two virtual DOMs every time. The first one contains the updated virtual DOM, and the
other is a pre-updated version of the updated virtual DOM. It compares the pre-updated version of the
updated virtual DOM and finds what was changed in the DOM, like which components will be changed.
Although it may seem ineffective, the cost is no more, as updating the virtual DOM cannot take much
time.
When comparing the current virtual DOM tree with the previous one is known as 'defying'. Once React
knows what has changed, it updates the objects in the actual DOM. React uses batch updates to update
the actual DOM. It changes to the actual DOM are sent in batches rather than sending any updates for
the single change into the component's state.
Re-rendering the UI is the most expensive part, and React manages to do most efficiently by ensuring
the Real DOM that receives the batch updates to re-render the UI. The process of converting the
changes to the actual DOM is called reconciliation.
It improves performance and is the main reason developers love react and its Virtual DOM.

What is React's Virtual DOM?

The concept of Virtual DOM comes to make the performance of Real DOM better and faster. Virtual
DOM is a virtual symbol of the DOM.
But the main difference is that every time, with each change, the virtual DOM gets updated instead of
the actual DOM.
For example, the real and virtual DOM is represented as a tree structure. Every element in the tree is a
node. A node is added to the tree when a new item is added to the application UI.
If the position of any elements changes, a new virtual DOM tree is created. The virtual DOM computes
the minimum number of operations on the real DOM to make changes to the real DOM. It is efficient
and performs better by reducing the cost and operation of re-rendering the whole real DOM.

JSX (java script xml):

JSX stands for JavaScript XML. It is a syntax extension of JS. Using JSX, we can write HTML
structures in the file which contain JavaScript code.

Components:

Components are independent and reusable of code. Every user interface in the React app is a
component. A single application has many components.
Components are of two types, class components and functional components.
Class components are stateful because they use their "state" to change the user interface. Functional
components are stateless components. They act like a JavaScript function that takes an arbitrary
parameter called "props".
React Hooks have been introduced to access states with functional components.

Lifecycle Methods

Lifecycle methods are important methods built-in to react, which operate on components through their
duration in the DOM. Each component of React went by a lifecycle of events.
The render() method is the maximum used lifecycle method.
It is the only method within React class components. So, in each class, component render() is called.

The render () method handles the component's render by the UI. The render () contains all the logic
displayed on the screen. It can also have a null value if we don't want to show anything on display.

class Header extends React.Component{


render(){
return <div> React Introduction </div>
}
The example will show the JSX written in the render().
When a state or prop is updated within the component, render() will return a different tree of React
elements.
When writing the code in the console or the JavaScript file, these will happen:
o The browser parses the HTML to find the node with the ID.
o It removes the child element of the element.
o It updates the element (DOM) with the 'updated value'.
o It recalculates CSS for parent and child nodes.
o Then, Update the layout.

Finally, traverse the tree on the screen display.


So as we know that updating the DOM involves changing the content. It is more attached to it.
Complex algorithms are involved in recalculating CSS and changing the layouts, which affect the
performance.
So, React has many ways of dealing with it, as it uses something known as virtual

DOM. reactdome
The react-dom package provides DOM-specific methods at the top level of the application to escape
route out of the React model if needed.

React Components
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.
A Component is considered as the core building blocks of a React application. It makes the task of
building UIs much easier. Each component exists in the same space, but they work independently from
one another and merge all in a parent component, which will be the final UI of your application.
Every React component have their own structure, methods as well as APIs. They can be reusable as per
your need. For better understanding, consider the entire UI as a tree. Here, the root is the starting
component, and each of the other pieces becomes branches, which are further divided into sub-branches.
import * as ReactDOM from 'react-dom';

1. Functional Components
2. Class Components

Functional Components
In React, function components are a way to write components that only contain a render method and
don't have their own state. They are simply JavaScript functions that may or may not receive data as
parameters. We can create a function that takes props(properties) as input and returns what should be
rendered. A valid functional component can be shown in the below example.
1. function WelcomeMessage(props) {
2. return <h1>Welcome to the , {props.name}</h1>;
3. }
The functional component is also known as a stateless component because they do not hold or manage
state. It can be explained in the below example.

Example

import React, { Component } from 'react';

class App extends React.Component {


render() {
return (
<div>
<First/>
<Second/>
</div>
);
}
}
class First extends React.Component {
render() {
return (
<div>
<h1>JavaTpoint</h1>
</div>
);
}
}
class Second extends React.Component {
render() {
return (
<div>
<h2>www.javatpoint.com</h2>
<p>This websites contains the great CS tutorial.</p>
</div>
);
}
}
export default App;
Output:

Class Components
Class components are more complex than functional components. It requires you to extend from React.
Component and create a render function which returns a React element. You can pass data from one
class to other class components. You can create a class by defining a class that extends Component and
has a render function. Valid class component is shown in the below example.
class MyComponent extends React.Component {
render() {
return (
<div>This is main component.</div>
);
}
}
The class component is also known as a stateful component because they can hold or manage local
state. It can be explained in the below example.

Example

In this example, we are creating the list of unordered elements, where we will dynamically insert
StudentName for every object from the data array. Here, we are using ES6 arrow syntax (=>) which
looks much cleaner than the old JavaScript syntax. It helps us to create our elements with fewer lines of
code. It is especially useful when we need to create a list with a lot of items.
import React, { Component } from 'react';
class App extends React.Component { constructor() {
super();
this.state = {
data: [ {
"name":"Abhishek"
}, {
"name":"Saharsh"
},
{ "name":"Ajay"
}
]
}
}
render() {
return ( <div>
<StudentName/>
<ul>
{this.state.data.map((item) => <List data = {item} />)} </ul>
</div>
);
}
}
class StudentName extends React.Component {
render() {
return (
<div> <h1>Student Name Detail</h1>
</div> );
}
}
class List extends React.Component {
render() {
return (
<ul>
<li>{this.props.data.name}</li>
</ul>
);
}
}
export default App;

Output:

React Props:
Props stand for "Properties." They are read-only components. It is an object which stores the value of
attributes of a tag and work similar to the HTML attributes. It gives a way to pass data from one component
to other components. It is similar to function arguments. Props are passed to the component in the same
way as arguments passed in a function.
Props are immutable so we cannot modify the props from inside the component. Inside the
components, we can add attributes called props. These attributes are available in the component as
this.props and can be used to render dynamic data in our render method.
When you need immutable data in the component, you have to add props to reactDom.render() method
in the main.js file of your ReactJS project and used it inside the component in which you need. It can be
explained in the below example.

Example

import React, { Component } from 'react';


class App extends React.Component {
render() {
return (
<div>
<h1> Welcome to { this.props.name } </h1>
<p> <h4> Javatpoint is one of the best Java training institute in Noida, Delhi, Gurugram, haziabad
and Faridabad. </h4> </p>
</div>
);
}
}
export default App;

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

ReactDOM.render(<App name = "JavaTpoint!!" />, document.getElementById('app'));

Output:

Default Props
It is not necessary to always add props in the reactDom.render() element. You can also set default props
directly on the component constructor. It can be explained in the below example.

Example

import React, { Component } from 'react';


class App extends React.Component {
render() { return (
<div>
<h1>Default Props Example</h1>
<h3>Welcome to {this.props.name}</h3>
<p>Javatpoint is one of the best Java training institute in Noida, Delhi, Gurugram, Ghaziabad an
d Faridabad.</p>
</div>
);
}
}
App.defaultProps = {
name: "JavaTpoint"
}
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'));

Output

React Component API


ReactJS component is a top-level API. It makes the code completely individual and reusable in the
application. It includes various methods for:
o Creatingelements
o Transforming elements
o Fragments

Here, we are going to explain the three most important methods available in the React component API.
1. setState()
2. forceUpdate()
3. findDOMNode()

setState()
This method is used to update the state of the component. This method does not always replace the state
immediately. Instead, it only adds changes to the original state. It is a primary method that is used to
update the user interface(UI) in response to event handlers and server responses.

this.stateState(object newState[, function callback]);

import React, { Component } from 'react';


import PropTypes from 'prop-types';
class App extends React.Component { constructor() {
super();
this.state = {
msg: "Welcome to JavaTpoint"
};
this.updateSetState = this.updateSetState.bind(this); }
updateSetState() {
this.setState({
msg:"Its a best ReactJS tutorial"
});
} render() {
return (
<div>
<h1>{this.state.msg}</h1>
<button onClick = {this.updateSetState}>SET STATE</button>
</div> );
} }
1.
Main.js
1. import React from 'react';
2. import ReactDOM from 'react-dom';
3. import App from './App.js';
4.
5. ReactDOM.render(<App/>, document.getElementById('app'));
Output:

When you click on the SET STATE button, you will see the following screen with the updated message.
forceUpdate()
This method allows us to update the component manually.

Syntax

1. Component.forceUpdate(callback);

Example

App.js
1. import React, { Component } from 'react';
2. class App extends React.Component {
3. constructor() {
4. super();
5. this.forceUpdateState = this.forceUpdateState.bind(this);
6. }
7. forceUpdateState() {
8. this.forceUpdate();
9. };
10. render() {
11. return (
12. <div>
13. <h1>Example to generate random number</h1>
14. <h3>Random number: {Math.random()}</h3>
15. <button onClick = {this.forceUpdateState}>ForceUpdate</button>
16. </div>
17. );
18. }
19. }
20. export default App;
Output:
Each time when you click on ForceUpdate button, it will generate the random number. It can be
shown in the

findDOMNode()
For DOM manipulation, you need to use ReactDOM.findDOMNode() method. This method allows us
to find o

Syntax

1. ReactDOM.findDOMNode(component);

Example

For DOM manipulation, first, you need to import this line: import ReactDOM from 'react-dom' in
your App.
App.js
1. import React, { Component } from 'react';
2. import ReactDOM from 'react-dom';
3. class App extends React.Component {
4. constructor() {
5. super();
6. this.findDomNodeHandler1 = this.findDomNodeHandler1.bind(this);
7. this.findDomNodeHandler2 = this.findDomNodeHandler2.bind(this);
8. };
9. findDomNodeHandler1() {
10. var myDiv = document.getElementById('myDivOne');
11. ReactDOM.findDOMNode(myDivOne).style.color = 'red';
12. }
13. findDomNodeHandler2() {
14. var myDiv = document.getElementById('myDivTwo');
15. ReactDOM.findDOMNode(myDivTwo).style.color = 'blue';
16. }
17. render() {
18. return (
19. <div>
20. <h1>ReactJS Find DOM Node Example</h1>
21. <button onClick = {this.findDomNodeHandler1}>FIND_DOM_NODE1</button>
22. <button onClick = {this.findDomNodeHandler2}>FIND_DOM_NODE2</button>
23. <h3 id = "myDivOne">JTP-NODE1</h3>
24. <h3 id = "myDivTwo">JTP-NODE2</h3>
25. </div>
26. );
27. }
28. }
29. export default App;
Output:

Once you click on the button, the color of the node gets changed. It can be shown in the below screen.
React Component Life-Cycle:
In ReactJS, every component creation process involves various lifecycle methods. These lifecycle
methods are termed as component's lifecycle. These lifecycle methods are not very complicated and
called at various points during a component's life. The lifecycle of the component is divided into four
phases. They are:
1. Initial Phase
2. Mounting Phase
3. Updating Phase
4. Unmounting Phase

Each phase contains some lifecycle methods that are specific to the particular phase. Let us discuss each
of these phases one by one.
1. Initial Phase
It is the birth phase of the lifecycle of a ReactJS component. Here, the component starts its journey on a
way to the DOM. In this phase, a component contains the default Props and initial State. These default
properties are done in the constructor of a component. The initial phase only occurs once and consists of
the following methods.
o 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.
o getInitialState()
It is used to specify the default value of this.state. It is invoked before the creation of the component.

2. Mounting Phase
In this phase, the instance of a component is created and inserted into the DOM. It consists of the following
methods.
o componentWillMount()
This is invoked immediately before a component gets rendered into the DOM. In the case, when you
call setState() inside this method, the component will not re-render.
o componentDidMount()
This is invoked immediately after a component gets rendered and placed on the DOM. Now, you can do
any DOM querying operations.
o render()

This method is defined in each and every component. It is responsible for returning a single root
HTML node element. If you don't want to render anything, you can return a null or false value.
3. Updating Phase
It is the next phase of the lifecycle of a react component. Here, we get new Props and change State.
This phase also allows to handle user interaction and provide communication with the components
hierarchy. The main aim of this phase is to ensure that the component is displaying the latest version of
itself. Unlike the Birth or Death phase, this phase repeats again and again. This phase consists of the
following methods.
o componentWillRecieveProps()
It is invoked when a component receives new props. If you want to update the state in response to prop
changes, you should compare this.props and nextProps to perform state transition by
using this.setState() method.
o shouldComponentUpdate()
It is invoked when a component decides any changes/updation to the DOM. It allows you to control the
component's behavior of updating itself. If this method returns true, the component will update.
Otherwise, the component will skip the updating.
o componentWillUpdate()
It is invoked just before the component updating occurs. Here, you can't change the component state by
invoking this.setState() method. It will not be called, if shouldComponentUpdate() returns false.
o render()
It is invoked to examine this.props and this.state and return one of the following types: React elements,
Arrays and fragments, Booleans or null, String and Number. If shouldComponentUpdate() returns false,
the code inside render() will be invoked again to ensure that the component displays itself properly.
o componentDidUpdate()
It is invoked immediately after the component updating occurs. In this method, you can put any code
inside this which you want to execute once the updating occurs. This method is not invoked for the
initial render.

4. Unmounting Phase
It is the final phase of the react component lifecycle. It is called when a component instance
is destroyed and unmounted from the DOM. This phase contains only one method and is given below.
o componentWillUnmount()
This method is invoked immediately before a component is destroyed and unmounted permanently. It
performs any necessary cleanup related task such as invalidating timers, event listener, canceling
network
requests, or cleaning up DOM elements. If a component instance is unmounted, you cannot mount it
again.

Example

1. import React, { Component } from 'react';


2.
3. class App extends React.Component {
4. constructor(props) {
5. super(props);
6. this.state = {hello: "JavaTpoint"};
7. this.changeState = this.changeState.bind(this)
8. }
9. render() {
10. return (
11. <div>
12. <h1>ReactJS component's Lifecycle</h1>
13. <h3>Hello {this.state.hello}</h3>
14. <button onClick = {this.changeState}>Click Here!</button>
15. </div>
16. );
17. }
18. componentWillMount() {
19. console.log('Component Will MOUNT!')
20. }
21. componentDidMount() {
22. console.log('Component Did MOUNT!')
23. }
24. changeState(){
25. this.setState({hello:"All!!- Its a great reactjs tutorial."});
26. }
27. componentWillReceiveProps(newProps) {
28. console.log('Component Will Recieve Props!')
29. }
30. shouldComponentUpdate(newProps, newState) {
31. return true;
32. }
33. componentWillUpdate(nextProps, nextState) {
34. console.log('Component Will UPDATE!');
35. }
36. componentDidUpdate(prevProps, prevState) {
37. console.log('Component Did UPDATE!')
38. }
39. componentWillUnmount() {
40. console.log('Component Will UNMOUNT!')
41. }
42. }
43. export default App;

Output:

React State
The state is an updatable structure that is used to contain data or information about the component. The
state in a component can change over time. The change in state over time can happen as a response to
user action or system event. A component with the state is known as stateful components. It is the heart
of the react component which determines the behavior of the component and how it will render. They
are also responsible for making a component dynamic and interactive.
A state must be kept as simple as possible. It can be set by using the setState() method and calling
setState() method triggers UI updates. A state represents the component's local state or information. It
can only be accessed or modified inside the component or by the component directly. To set an initial
state before any interaction occurs, we need to use the getInitialState() method.
For example, if we have five components that need data or information from the state, then we need to
create one container component that will keep the state for all of them.
Defining State
To define a state, you have to first declare a default set of values for defining the component's initial
state. To do this, add a class constructor which assigns an initial state using this.state. The ' this.state'
property can be rendered inside render() method.

Example

The below sample code shows how we can create a stateful component using ES6 syntax.
1. import React, { Component } from 'react';
2. class App extends React.Component {
3. constructor() {
4. super();
5. this.state = { displayBio: true };
6. }
7. render() {
8. const bio = this.state.displayBio ? (
9. <div>
10. <p><h3>Javatpoint is one of the best Java training institute in Noida, Delhi, Gurugr am,
Ghaziabad and Faridabad. We have a team of experienced Java developers and trainers from multin
ational companies to teach our campus students.</h3></p>
11. </div>
12. ) : null;
13. return (
14. <div>
15. <h1> Welcome to JavaTpoint!! </h1>
16. { bio }
17. </div>
18. );
19. }
20. }
21. export default App;
To set the state, it is required to call the super() method in the constructor. It is because this.state is
uninitialized before the super() method has been called.
Output

Changing the State


We can change the component state by using the setState() method and passing a new state object as the
argument. Now, create a new method toggleDisplayBio() in the above example and bind this keyword
to the toggleDisplayBio() method otherwise we can't access this inside toggleDisplayBio() method.
1. this.toggleDisplayBio = this.toggleDisplayBio.bind(this);

Example

In this example, we are going to add a button to the render() method. Clicking on this button triggers the
toggleDisplayBio() method which displays the desired output.
1. import React, { Component } from 'react';
2. class App extends React.Component {
3. constructor() {
4. super();
5. this.state = { displayBio: false };
6. console.log('Component this', this);
7. this.toggleDisplayBio = this.toggleDisplayBio.bind(this);
8. }
9. toggleDisplayBio(){
10. this.setState({displayBio: !this.state.displayBio});
11. }
12. render() {
13. return (
14. <div>
15. <h1>Welcome to JavaTpoint!!</h1>
16. {
17. this.state.displayBio ? (
18. <div>
19. <p><h4>Javatpoint is one of the best Java training institute in Noida, Delhi,
Gurugram, Ghaziabad and Faridabad. We have a team of experienced Java developers and trainers
from multinational companies to teach our campus students.</h4></p>
20. <button onClick={this.toggleDisplayBio}> Show Less </button>
21. </div>
22. ):(
23. <div>
24. <button onClick={this.toggleDisplayBio}> Read More </button>
25. </div>
26. )
27. }
28. </div>
29. )
30. }
31. }
32. export default App;
Output:
React Events
An event is an action that could be triggered as a result of the user action or system generated event.
For example, a mouse click, loading of a web page, pressing a key, window resizes, and other
interactions are called events.
React has its own event handling system which is very similar to handling events on DOM elements.
The react event handling system is known as Synthetic Events. The synthetic event is a cross-browser
wrapper of the browser's native event.

Handling events with react have some syntactic differences from handling events on DOM. These are:
1. React events are named as camelCase instead of lowercase.
2. With JSX, a function is passed as the event handler instead of a string. For example:

Event declaration in plain HTML:


<button onclick="showMessage()">
Hello JavaTpoint
</button>

Event declaration in React:

<button onClick={showMessage}>
Hello JavaTpoint
</button>
In react, we cannot return false to prevent the default behavior. We must call preventDefault event
explicitly to prevent the default behavior. For example:

In plain HTML, to prevent the default link behavior of opening a new page, we can write:

<a href="#" onclick="console.log('You had clicked a Link.'); return false">


Click_Me
</a>

import React, { Component } from 'react';


class App extends React.Component {
constructor(props) {
super(props);
this.state = {
companyName: ''
};
} changeText(event) { this.setState({ companyName: event.target.value });
} render() { return ( <div>
<h2>Simple Event Example</h2>
<label htmlFor="name">Enter company name: </label>
<input type="text" id="companyName" onChange={this.changeText.bind(this)}/>
<h4>You entered: { this.state.companyName }</h4> </div>
);
}
}
export default App;

Output

After entering the name in the textbox, you will get the output as like below screen.

Lifting State up in ReactJS


Lifting up the State:
As we know, every component in React has its own state. Because of this sometimes data can be
redundant and inconsistent. So, by Lifting up the state we make the state of the parent component as a
single source of truth and pass the data of the parent in its children.
Time to use Lift up the State: If the data in “parent and children components” or in
“cousin components” is Not in Sync.
Example 1: If we have 2 components in our App. A -> B where, A is parent of B. keeping the same
data in both Component A and B might cause inconsistency of data.

Example 2: If we have 3 components in our App.


A
/\
B C
Where A is the parent of B and C. In this case, If there is some Data only in component B but,
component C also wants that data. We know Component C cannot access the data because a component
can talk only to its parent or child (Not cousins).
Problem: Let’s Implement this with a simple but general example. We are considering the second
example.
Complete File Structure:
Approach: To solve this, we will Lift the state of component B and component C to component
A. Make A.js as our Main Parent by changing the path of App in the index.js file
Before:
import App from './App';
After:
import App from './A';
Filename- A.js

import React,{ Component } from 'react';

import B from './B'

import C from './C'

class A extends Component {

constructor(props) {

super(props);

this.handleTextChange = this.handleTextChange.bind(this);

this.state = {text: ''};

handleTextChange(newText) {

this.setState({text: newText});

}
render() {

return (

<React.Fragment>

<B text={this.state.text}

handleTextChange={this.handleTextChange}/>

<C text={this.state.text} />

</React.Fragment>

);

export default A;

Filename- B.js:
import React,{ Component } from 'react';

class B extends Component {

constructor(props) {
super(props);
this.handleTextChange = this.handleTextChange.bind(this);
}
handleTextChange(e){
this.props.handleTextChange(e.target.value);
}

render() {
return (
<input value={this.props.text}
onChange={this.handleTextChange} />
);
}
}

export default B;

Filename- C.js:
import React,{ Component } from 'react';

class C extends Component {

render() {
return (
<h3>Output: {this.props.text}</h3>
);
}
}

export default C;
Composition vs inheritance in React.js:

Composition and inheritance are the approaches to use multiple components together in React.js . This
helps in code reuse. React recommend using composition instead of inheritance as much as possible and
inheritance should be used in very specific cases only.
Inheritance
class UserNameForm extends React.Component {
render() {
return (
<div>
<input type="text" />
</div>
);
}
}
ReactDOM.render(
< UserNameForm />,
document.getElementById('root'));
This sis simple to just input the name. We will have two more components to create and update the
username field.
With the use of inheritance we will do it like −

class UserNameForm extends React.Component {


render() {
return (
<div>
<input type="text" />
</div>
);
}
}
class CreateUserName extends UserNameForm {
render() {
const parent = super.render();
return (
<div>
{parent}
<button>Create</button>
</div>
)
}
}
class UpdateUserName extends UserNameForm {
render() {
const parent = super.render();
return (
<div>
{parent}
<button>Update</button>
</div>
)
}
}
ReactDOM.render(
(<div>
< CreateUserName />
< UpdateUserName />
</div>), document.getElementById('root')
);
We extended the UserNameForm component and extracted its method in child component using
super.render();
Composition
class UserNameForm extends React.Component {
render() {
return (
<div>
<input type="text" />
</div>
);
}
}
class CreateUserName extends React.Component {
render() {
return (
<div>
< UserNameForm />
<button>Create</button>
</div>
)
}
}
class UpdateUserName extends React.Component {
render() {
return (
<div>
< UserNameForm />
<button>Update</button>
</div>
)
}
}
ReactDOM.render(
(<div>
<CreateUserName />
<UpdateUserName />
</div>), document.getElementById('root');

You might also like