0% found this document useful (0 votes)
392 views

Reactjs by Sudhakar Sir

Uploaded by

alark4study
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
392 views

Reactjs by Sudhakar Sir

Uploaded by

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

React JS

Prerequisites:
- HTML
- CSS
- JavaScript ES6

Topics
- What is React?
- Why React?
- Difference between React, Angular, Vue etc.
- Features and Limitations
- Understanding React Application Architecture
- Components, Props and State
- Styling with Material UI
- Debug React Apps
- Life Cycle
- React Hooks
- Ajax Calls/ Http Requests
- Integration with Server Side [MERN]
- Routing
- Forms and Validations
- Deploying
- Redux
- Error Handling
- Unit Testing
- Web Pack
- React Native
- End to End Integration

Which oneI have to choose? [Angular or React]


Projects — Which arecompletely integrated with lot of
server-side interactions and every concept is handled
at server level only they are looking for good UIto
make faster interactions then “React JS”.

Projects — Which need to control their application flow


both client side and server side — Angular.

React JS is library
Angular is Framework

Mill of Users are accessing some content using content.


Only few interactions like message, chat. Not complete
EPR. [Not Querying — Transactions, complex
operations] — React is Great
Twitter, Instagram
Java - Spring
PHP - Cake PHP, Code Igniter
Python - Django, Flask
Ruby - Ruby on Rails
.NET - ASP.NET MVC
JavaScript - SPINE, Angular
MVC - Model View Controller
React is only with “View” UI — Interactions

Web Development 3+ Years: Angular, React


Java, .NET, PHP, Python 3+ years [Angular, React]

What is React and How it Works?


- React JS isa library.
- Client Side we have languages, libraries and
frameworks.
- Client-Side Languages
o JavaScript
o TypeScript
- Client-Side Libraries
o jQuery
o RxJS
o jQlite
o React JS
- Client-Side Frameworks
o Angular JS
o Knockout JS
o Backbone JS
o Angular
What is diflerence between Language and Library?
- Language requires functions defined explicitly to
handle various interactions.
- Language requires lot of references.
- Library isa set of factories.
- Factory isa set of pre-defined functions.
- You can implement the existing function and
define the functionality.
- Library reduces the compatibility issues.
- React JS isa library.

What is diflerence between Library and Framework?


- Library can build application.
- Library is passive [not-active]
- Library can't control the application flow.
- It requires browser events to make library active.
- Framework isa software architectural pattern that
provides set of libraries to build application and
can also control the application flow.

What is React JS?


- React JS isa JavaScript library.
- Building User interfaces and handling User
interactions client side.
- Facebook — Jordan Walke — forbuilding SPA.
- 2013 Initial release.
- 2020— 17.0.1 latest stable version.

It is not designed forwhat you areusing. Hence


limited library.
React JS library requires several external libraries to
integrate and handle functionality.

Features of ReactJS
- ReactJS uses virtual DOM that makes theuser
experience better.
- Faster Interactions.
- React uses JSX, which is easy to handle the
manipulation on DOM elements.
o JSX is faster that JavaScript DOM
manipulations.
o Logic and markup can be defined in single file.
o It is easy to create template.
o Template comprises of presentation and logic.
- React uses “One Way Data Binding”
o Data binding isa technique used to update
the component data to View [UI]
o Any change in component data will update to
UI. [HTML]
o Changes made in UI are not directly update
back to component, they are handled on
virtual DOM.
- Component based architecture.
o It is an alternative for legacy type library.
o It is more asynchronous
o It loads only what is required for the situation.
o It improves the performance of application.
o It makes your library modular.

Concerns with ReactJS


- Very high pace of development.
- Problem fordevelopers to catch and update the
pace of developing features.
- Poor documentation.
- Poor SEO
- JSX [Presentation with Logic] — Insecure content
and ignore
XSS [Cross Site Scripting Attacks]
- Need lot of external libraries to handle various
interactions.
Setup Environment forReactJS
Install Node JS
o Node JSprovidesa package manager NPM.
o Package manager isa tool used to install and
configure library required for our application.
o There are several package managers like:
Yarn, NPM, Bower, Ruby Gems, NuGet etc.
o Installing Node JSon your PC will get you
NPM.
https://nodejs.org/en/download/ [Make sure
that Node JSversion 10+]
o After installing Node JScheck the version from
command prompt
> node -v
> npm -v

Install Visual Studio Code [IDE - Integrated


Development Environment]
- IDE provides environment to build, debug, test and
deploy application.
- You can use various editors: “editorconfig.org”
- Download and install VS Code
https://code.visuaIstudio.com/
- Go to “Customize” and “Install Support for
JavaScript”
- Go to “Extensions” and Install following
o Live Server: It required to preview your
application.

o Vscode-icons: It gives suitable icons for


specific file extensions and names, so that
developer can easily identify the file type.

o IntelliSense for CSS Class Name: It provides


help on CSS

Creatinga new Project


- Createa new folder for project by name
“ReactApp” on your PC
“C:\ReactApp”
- Open your folder in Visual Studio Code: File Menu
->Open Folder -> C:\ReactApp
- Open Terminal: Go to Terminal Menu andselect
“New Terminal” or Ctrl+ ” [backtick]
- Run the command “npm init”
C:\ReactApp> npm init
- It will generate “package.json” that comprises of
project meta data.
package name: (reactapp) reactapp
version: (1.0.0)
description: This is our first react
application
entry point: (index.js)
test command:
git repository:
keywords: react shopping, smart shopping
author: NareshI Technologies
license: (ISC) MIT
- Install React Modules into Project
C:\ReactApp>npm install --save react
C:\ReactApp>npm install --save react-dom
- Installed library will be maintained in
“node modules” folder
Createa React Application
> npm install -g create-react-app
> create-react-app shopping
> Change to shopping
C:\reactapp\shopping>
> npm start [Start the react application]

React Workspace
- It comprises of shared libraries for all your ReactJS
projects.
- In workspace you can maintain multiple projects
- Workspace comprises of

File/ Folder Description


node_moduIes - lt comprises of project
“dependencies” and
“devDependencies”.
- The library required for
your react application is in
“node_moduIes”.
- These dependencies can
be shared to all projects in
workspace.
package.json - It comprises of
information about the
packages installed in your
workspace.
packageIock.jso - It comprises of packages
n meta data.
Shopping - It is your react application
in the workspace.

The files and folders of React Application

File/ Folder Description


node_moduIes It contains local dependencies.
public It comprises of all our project
static files, like Images, html,
text etc.
It comprises of all our project
dynamic files like, CSS,
JavaScript etc. [LESS, SASS]
.eslintcache It is used to track and identify
the issues in your JavaScript
code. It can configure the rules
for JavaScript.
.gitignore It specifies the dependence to
ignore while deploying of GIT.
Packagelock.jso Local dependencies meta data
n
Package.json Local dependencies
information.
README.md Help document.

Files in Public folder

favicon.ico Shortcut icon used for


bookmarking.
Index.html It is the start up page.
manifest.jso It comprises of metadata.
n Information about react
application. Browsers can
understand your application by
accessing details from manifest.
Robots.txt It comprises of User Agent details,
which is information about the
browsers supported.

Files in SRC folder


App.css It comprises of global styles
used forapp component.
App.js It comprises the logic
required for default
component that is “app”
component.
Every project contains set of
several components.
React application by default
comes with “app”
component.
Application starts with
“app” component.
Every component comprises
of3 files
- .css Styles
- .js Logic (JSX —
HTML andJS)
- .spec/test.js : It is
test file
App.test.js It is the test file for “app”
component.
Index.css Styles for Index Page
Index.js JSX for Index Page
Setuptests.js It configures the testing
environment forapplication
testing.
reportWebVitaIs.j Error reporting
S

What is Toolchain for React?


- Toolchain isa set of programming tools that are
used in performinga complex software
development task or to createa software product.
- In general, “toolchain” isa set of tools used for
building/developing an application.
Ex:
Language : used forwriting the logic
Compiler : fortranslating in machine format.
Debugger : to identify and fix the bugs.
[error/issues]
Testing a framework fortesting
Deployment: tool for deploying application on
production.
What is Recommended toolchain for ReactJS
Application?
- Package Manager [NPM, Yarn]
- Bundler [Webpack, Parcel]
- Compiler [Babel — differential loading]
Package Manager Installing and Maintaining
Dependencies
EX:
NPM, Yarn
Bundler Writing modular code and
bundle it together for
application.
Ex:
Webpack, Parcel
Compiler It allows to handle differential
loading.
Library will be classified
according to browser. [Legacy
, Modern]

What arethepopular toolchains used forReactJS?


- Neutrino
- Nx
- Parcel
- Razzle
When we need the individual toolchains?
- When we aretrying to integrate ReactJS into
existing application.
What is NPX?
- It isa tool that comes with NPM.
- It can directly create react application.
- We don't require “create-react-app” to install if
we are using “npx”.
> npx create-react-app yourAppName

How toadd “ReactJS” into existing application?


- Createa new folder for project “C:\HtmIReactApp”
- Open your folder in “Visual Studio Code”
- Open Terminal [Ctrl+ ”] or Open folder location in
command prompt
- Run the command
> npm init

"name": "htmlreact",
"version": "1.0.0",
"description”: "HTML Website with React",
remain": "index.js",
"scripts":{
"test": "echo \"Error: no test specified\" && exit 1”

"keywords":[
"HTML",
Application
React",
"Application

"author": "Naresh-I-Technologies",
"license": "MIT"

- “package.json” file is created


- Add a new folder into project by name “public”
- Add a new file into public folder “index.html”
- You can install dependencies forproject using
“npm”
Ex:
> npm install bootstrap
- It will generate “node modules” and “package-
lock.json”
- To integrate “ReactJS” into your page you need
o react.development.js
o react-dom.development.js
- You have get these file from official ReactJS
website CDN links
https://reactjs.org/docs/cdn-links.html
- Add following scripts into head section
<script crossorigin
src="https://unpkg.com/react@17/umd/react.de
velopment.js">
</script>
<script crossorigin
src="https://unpkg.com/react-
dom@17/umd/react-dom.development.js">
</script>
- Add Babel CDN to your page
https://babeIjs.io/docs/en/babel-standalone
<script
src="https://unpkg.com/@babeI/standalone/bab
eI.min.js"></script>

Create React JS Component


- Components arebuilding blocks for creating
applications.
- Technically component isa template.
- It comprises of design and functionality, which you
can inject and use in any page.
- Components will provide re-usable templates for
React JS application.
- Components areclassified into2 major types
o Function Component
o Class Component
- Component is designed by using JSX [JavaScript
Extension]
- React JS component can be embedded into Page
or can be defined in module.
o Embedded Technique
Component is designed and used in the same
page.
o Module Technique
Component is designed ina separate
JavaScript [“.js”]
Component is linked to any page.
Ex: React JS components embedded into Page
<!DOCTYPE htmI>
<htmI>
<head>
<titIe>HTML React App</title>
<script crossorigin
src=”https://unpkg.com/react@17/umd/react.develop
ment.js”></script>
<script crossorigin src="https://unpkg.com/react-
dom@17/umd/react-dom.development.js </script>
<script crossorigin
src=”https://unpkg.com/@babeI/standalone/babeI.mi
n.js"></script>
<script type="text/jsx">
ReactDOM.render(
<p>WeIcome toReact JS</p>,
document.getEIementById(’root)

</script>
<SCript type= tf?Xt/javascript
function bodyload(){
alert(”React Integrated");

</script>
</head>
<body onload=”bodyIoad()">
<h2>HTML React App</h2>

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

Note: The MIME type of React JS “JSX” script must be


“text/jsx” or “text/babel”
Syntax:
<script type=”text/jsx”> </script>
<script type=”text/babeI”></script>

Embedded Component:
- In embedded technique the component is
designed in the page.
- It is faster in access.
- It reduces the load time.
- It reduces the number ofrequests made topage.
- Code reusability issues
- Extensibility issues
- Maintainability and testability are the issues.

Module Technique:
- Component is designed ina separate JavaScript file
“.js”
- JavaScript file is considered asa Module.
- Module comprises of classes, functions etc.
- Easy to extend
- Easy to re-use
- Easy to test
- Using an external file will always increase the
number ofrequests made topage and also the
page load time.
Ex:
- Go to “src” folder and adda new file “hello.js”
- Add the following code into “hello.js”

ReactDOM.render(
<p>WeIcome toReact JS - External
Component</p>,
document.getEIementById('root')
)*

- Link to your HTML page.

<!DOCTYPE htmI>
<htmI>
<head>
<titIe>HTML React App</title>
<script crossorigin
src="https://unpkg.com/react@17/umd/react.devel
opment.js"></script>
<script crossorigin
src="https://unpkg.com/react-dom@17/umd/react-
dom.development.js </script>
<script crossorigin
src="https://unpkg.com/@babeI/standalone/babeI.
min.js"></script>
<SCFipt type="text/jsx
src=”../src/hello.js"></script>
</head>
<body>
<h2>HTML React App</h2>

<div id="root">

</div>
</body>
</htmI>
JSX
- JSX isa statically-typed, object-oriented
programming language.
- It compiles to standalone JavaScript.
- It can use all feature of JavaScript.
- It finally compiles to JavaScript.
- It isa combination of presentation and logic.
- It makes inline technique more effective.
- It makes JavaScript more expressive and effective.
What is statically typed language?
- Generally, if the type of variable is known atthe
compile time then it is known asstatically typed.
- Dynamically typed is determined during run time.

Install JSX on your PC:


> npm install -g jsx
Creating JSX program
- JSX programs must have the extension “.jsx”
- You can compile and run JSX by using
> jsx --run program.jsx

JSX Program Structure


- Program comprises ofa class with main function.
- JSX uses all statically typed content.
- JavaScript is not statically typed.
- JSX requires the data type to be defined for every
variable and parameter you define.
- JSX can use the JavaScript data types
o Primitive Types
o Non-Primitive Types/ Object Types
JSX Primitive:
- number
- string
- boolean
- null
- undefined
JSX Variables
- var
- let
- const
Syntax:
var variableName DataType;
let variableName: DataType;
const variableName: DataType = value;

JSX also supports Type Inference?


- It isa technique where JSXidentifies the data type
according to the value and assigned the type to
variable.
Ex:
var variableName = value;
var username = “John”; //username string
var salary = 45000.55; // salary number

JSXNon-Primitive Type:
- They areobject types
- Typically JSX Object Types are
o Date()
o Array()
o Map()
o Object
Syntax:
Var d = new Date();
Vara = new Array();
Var o ={ )

JSX Operators
JSX Expression
JSX Statements
JSX functions
JSX Classes
JSX Modules

JSX Program Structure


- Every JSX program must contain “_Main” class
- “_Main” is the start-up class in JSX.
- In JSX program there can be any number ofclasses
but it starts with only “_Main” class.
- Class can contain any type of functions.
- JSX “_Main” class must contain “main()” function.
- “main()” function is the entry point for program.
- The “main()” function must be configure with
string array type args.
Note: Module level entry point is “_Main” class and
function level entry point is “main()” function.

Createa new JSX Program


Demo.jsx
class Main
static function main(): void{
log ”Welcome toJSX";

Compile and run JSX Program


- Open Terminal
> jsx--run demo.jsx

JSXOOPS
Contracts in OOP:
- A contract defines rules for designing any
component.
- Contracts are specified by using “interface”.
- Interface can contain only rules.
- It must have only declaration not implementation.
Syntax:
interface InterfaceName

Name string; // valid


Price : number = 45600.55; // invalid — rules
can't have implementation
- Interface can also define function declaration,
which is implemented later.
- Interface functions can't have definition.
Ex:
interface IProduct

Name:string;
Price:number;
Stock:boolean;
Total():number;
Print():void;

- Every rule defined in contract is mandatory to


implement.
- You can't define any new implementation if it is
not in contract.

JSX Class
- Class isa program template.
- Class is used as entity, model ortemplate.
- Class comprises of data and logic.
- JSX class have following characteristics.
o All JSX classes are derived froma base class
“Object”.
o Object isa built-in class of JSX.
o Class can extend another class by using
“extends” keyword.
o JSX class can be defined with following
attributes
abstract It is used when anymethod in
class is abstract.
final It declares that the calls may not
be extended.
- JSX class can contain
o Member Variables and
o Member Functions
Ex:
class Product

var _name String; -3' Variable


function constructor(name: string){ -3'
Constructor Member Function
this._name = name;

function Print(): void( Y


Member Function
log”Product Name:”+ this._name;
- Class variable in JSX can be defined with var, const,
and let.
o Member variable ina JSX class can be defined
with
• abstract: Ifa variable is using expression,
which needs implementation.
• static : It uses continuous memory.
- Class member function in JSX can be defined with
following attributes
Function Description
Attribute
abstract It declares that the function
should be overridden bya class
that extends the current class.
final It declares that function may not
be overridden.
static It declares that function is static.
It uses continuous memory.
override It declares that the definition of
the function is overriding and
definition is extending.

Ex:
interface ProductName{
abstract function PrintName():void;
abstract class ProductPrice

function PrintPrice():void{
log "Price = 45000";

class Product extends ProductPrice implements


ProductName{
override function PrintName():void{
log "Name = Samsung TV";

class Main{
static function main(args: string[]): void{
var tv = new Product();
tv.PrintName();
tv.PrintPrice();

Functions and Closures in JSX


- JSX supports all JavaScript functions and their
manipulations.
- Functions with parameters.
- Function with rest parameters.
Ex:
function PrintList(...list){
for(var item of list){
document.write(item+ "<br>");

PrintList("Samsung TV",”MobiIe","Shoe");
o Every function can have only one rest
parameter.
o Rest parameter must be the last parameter in
formal list.
- Function recursion.
- Anonymous function.
- Function closures.
- Arrow functions [LAMBDA] () parameters =>
return value
Ex:
var hello = (name)=> "Hello! ${name}";
document.write(hello("john"));
- JSX functions are “first-class objects" and they
have static types.
- You can define closures using "function"
expression or "function" statement.
- Typically function closures are used to implement
callbacks.
Ex:
class _Main

varuserName Hello! John”;


function constructor(){
var hello = function():void{
log this.userName;

hello();

static function main(args: string[]):void{


var obj = new _Main();

JSX Modules
- JavaScript module systems are “Common JS, AMD
[Asynchronous Module Distribution]” etc.
- Module comprises of setof classed which are
exported and imported into another library.
- JSX provide built-in modules to handle various
interactions.
o timer.jsx
o js/web.jsx etc.
- JSX also allows to create and configure custom
modules to build library for react application.
Ex:
import "timer.jsx”;
class Main

static function main(args: string[]):void{


Timer.setTimeout(function():void{
log "Hello! JSX";
}, 2000);
Timer.setTimeout(function():void{
l og "Welcome toJSXI
}, 5000);

Summary
- Variables
- Data Types
- Operators
- Statements
- Interface
- Class
- Member Variables
- Member Functions
- Modules
JSX with React JS
- JSX will allow to configure any expression and
store ina variable reference.
- The variables that are handling JSX expression
must be initialized.
- If you are referring to any variable that is not
defined with value the it returns “undefined”.
- Hence JSXvariables must be initialized.
- Initialization of variables is done by using “const”.
- JSX expressions are directly defined without
enclosing in quotes.
- The dynamic values are embedded into expression
by using “{ )”
Ex:
- Go to “src” folder and adda new file “app.js”
- Add following code into “app.js”

const title = "Amazon Shopping",


const element = <h1>{titIe}</h1>;

ReactDOM.render(
element,
document.getEIementById('root')

- Link app.js to index.html page


<!DOCTYPE htmI>
<htmI>
<head>
<titIe>HTML React App</title>
<script crossorigin
src="https://unpkg.com/react@17/umd/react.devel
opment.js"></script>
<script crossorigin
src="https://unpkg.com/react-dom@17/umd/react-
dom.development.js"></script>
<script crossorigin
src=”https://unpkg.com/@babeI/standalone/babeI.
min.js"></script>
<script type="text/jsx"
src="../src/app.js”></script>
</head>
<body>
<div id="root">
</div>
</body>
</htmI>

Configuring React Elements

Note: JSX expression allows only single line in any


variable reference.
Ex:
const element = <div>
<h2> Welcome </h2>
</div>; //Invalid
You can define expression in multiple lines by
enclosing in “( )”

Ex:
const element =(
<div>
<h2> Welcome </h2>
</div>
)

Note: You can define multiple lines in JSX expression


but all lines must be defined under one element.

Ex: Invalid
const element =(
<h1> Amazon </h1>

V
<p> Online Shopping
)*

You can't have individual elements in “( )” all must be


enclosed in one element.

Ex: Valid
const element =(
<div>
<h1> Amazon </h1>
<p> Online Shopping </p>
</div>
)*
- Adding an additional container for multi lines my
effect the hierarchy of your DOM.
- You can use an empty element representation.

<> starting
</> ending

Ex: Best Technique


const element =(

<h1> Amazon </h1>


<p> Online Shopping </p>

Note: JSX will not allow void element syntax.

Ex:
const element = <img src={pic}>; // Invalid
const element = <img src={pic}></img> // valid
const element = <img src={pic}/> // valid
Ex: app.js
const pic= 'shoe.jpg'
const element =(

<h2>Amazon Shopping</h2>
<p>OnIine Shopping Site</p>
<img src={pic}/>

ReactDOM.render(
element,
document.getEIementById('root’)

Index.html
<!DOCTYPE htmI>
<htmI>
<head>
<titIe>HTML React App</title>
<script crossorigin
I
srcm https://unpkg.com/react@17/umd/react.develop
ment.js”></script>
<script crossorigin src="https://unpkg.com/react-
dom@17/umd/react-dom.development.js </script>
<script crossorigin
src=”https://unpkg.com/@babeI/standalone/babeI.mi
n.js"></script>
<script type="text/jsx"
src=”../src/app.js"></script>
</head>
<body>
<div id="root">

</div>
</body>
</htmI>
Note: JSX dynamic values can be bound only to the
properties of element, you can't bind to attributes.
FAQ: What is difference between “attribute” and
“property”?
Attribute Property
Immutable Mutable
Can't change its state. Can changes its state.
Statically defined Dynamically defined
Used forTags Used forElements
<img src> :src is attribute
Var pic = new Image();
pie.src= “” : src is property

- HTML tags have attribute and HTML Elements


have properties.
- Every HTML tagattribute is not available as
property.
Ex: table have height as attribute but height is not
available as property.

- Every HTML tagattribute is not available with the


same name asproperty.
Ex: table have “class” as attribute but it is used as
“className” dynamically.
- React JS will not be able bind any dynamic data to
attribute while creating element dynamically, you
have to always bind to property.
Ex:
App.js
const pic = 'shoe.jpg",
const effect = 'container",
const element =(
<div className={effect}>
<h2 align="center”>Amazon Shopping</h2>
<p align="center">OnIine Shopping Site</p>
<img src={pic) width="100" height="100" />
</div>
)*

ReactDOM.render(
element,
document.getEIementById(’root’)
)/

Index.html
<!DOCTYPE htmI>
<htmI>
<head>
<titIe>HTML React App</title>
<script crossorigin
src=”https://unpkg.com/react@17/umd/react.devel
opment.js"></script>
<script crossorigin
src=”https://unpkg.com/react-dom@17/umd/react-
dom.development.js"></script>
<script crossorigin
src="https://unpkg.com/@babeI/standalone/babeI.
min.js"></script>
<script type="text/jsx"
src="../src/app.js”></script>
<styIe>
.container{
width: 400px;
height: 200px;
border:2px solid darkcyan;
box-shadow: 3px 4px Spx darkcyan;
border-radius: 20px;
padding: 20px;

</styIe>
</head>
<body>
<div id="root">
</div>
</body>
</htmI>

JSX allows to create element and configure the


properties dynamically:
- Elements are created dynamically and added to UI.
- User can add the components in UI according to
state and situation.
- Dynamically elements can be created by using the
react method
“React.createEIement()”
Syntax:
React.createEIement(
“elementName”,
{ property: value, ... },
“default text”

Ex:
App.js
const pic = 'shoe.jpg",
const element = React.createEIement(
'div’,
{className: ontainer’, align: 'center’},
'Welcome to React JS’

ReactDOM.render(
element,
document.getEIementById(’root’)
)I

Index.html
<!DOCTYPE htmI>
<htmI>
<head>
<titIe>HTML React App</title>
<script crossorigin
src="https://unpkg.com/react@17/umd/react.devel
opment.js"></script>
<script crossorigin
src=”https://unpkg.com/react-dom@17/umd/react-
dom.development.js"></script>
<script crossorigin
src=”https://unpkg.com/@babeI/standalone/babeI.
min.js"></script>
<script type="text/jsx"
src="../src/app.js”></script>
<styIe>
.container{
width: 400px;
height: 200px;
border:2px solid darkcyan;
box-shadow: 3px 4px Spx darkcyan;
border-radius: 20px;
padding: 20px;

</styIe>
</head>
<body>
<div id="root">

</div>
</body>
</htmI>

Creating Nested Elements and rendering


App.js
const pic = 'shoe.jpg'
const element = React.createEIement(
'div',
{className: 'container', align: 'center’),
’Welcome to React JS',
React.createEIement(
'h2',
{align: 'center'},
'JSX Introduction'
)/

React.createEIement(
f l
p *

null,
'React Presentation
)y

React.createEIement(
{src: 'shoe.jpg’, width: 100, height: 100}

ReactDOM.render(
element,
document.getEIementById('root’)

Index.html
<!DOCTYPE htmI>
<htmI>
<head>
<titIe>HTML React App</title>
<script crossorigin
src=”https://unpkg.com/react@17/umd/react.develop
ment.js”></script>
<script crossorigin src="https://unpkg.com/react-
dom@17/umd/react-dom.development.js"></script>
<script crossorigin
srcm https://unpkg.com/@babeI/standalone/babeI.mi
n.js"></script>
<script type="text/jsx"
S
y
C
m QS C/app.js </SCFipt>

<styIe>
.container{
width: 400px;
height: 220px;
border:2px solid darkcyan;
box-shadow: 3px 4px Spx darkcyan;
border-radius: 20px;
padding: 20px;

</styIe>
</head>
<body>
<div id="root">

</div>
</body>
</htmI>
You can configure elements in Object Style
- You can use JavaScript object type to configure
elements and render into React Virtual DOM.
- Object comprises of Key and value.
- The keys required for designing element
o type : It defines the element type
o props : It defines the properties [object].
Properties will allow all JS properties.
Ex:
const element ={
type: ’div',
props (
className: ’container
children: ’Welcome to React'

Rendering the Elements


- The elements configured for React are rendered
into “Virtual DOM”.
- The “ReactDOM” method “render()” is used to
createa virtual DOM and render your element into
the DOM.
Syntax:
ReactDOM.render(What [element],
Where[Target]): It is rendering element into
virtual DOM.
- ElementName: Specifies the element to render.
- Target Container: Specifies the id of element
where theresulting markup must be rendered.

Ex:
const element =(
<div className='container'>
<h2 align='center’>React JS EIements</h2>
</div>

ReactDOM.render(
element,
document.getEIementById('root’)

- You can use a Query Selector of JavaScript to


access the element by id and use for rendering
the React element into virtual DOM.

Ex:
App.js
const element =(
<div className='container'>
<h2 align='center’>WeIcome to React JS</h2>
</div>

const target = document.querySeIector(uproot');


ReactDOM.render(element, target);
Ex:
App.js
const element =(
<div className='container'>
<h2 align='center’>HeIIo! React JS</h2>
</div>

const target = document.getEIementById(’root');


ReactDOM.render(element, target);

You also use “React.Component” class to render any


content:
Syntax:
class Demo extends React.Component{
render(){
return “<h2> You Content </h2>”

React JS Components
- Components arethe building blocks of any
React application.
- Typically,a react application is built with
components.
- Component is built with UI and logic asa
template.
- You can reuse the components in application.
- You can customize according the
requirements.
- React JS application can use pre-defined
components and also allows to create custom
components.
- Pre-defined components like
o Material-UI
o Telerik
- Custom components aredesigned by using
JavaScript functions and classes.
- Technicallya component is React JS can be
o JavaScript function
o JavaScript Class
Functional Components
- The components designed by using JavaScript
functions are known asFunctional Components.
- Every functional component is by default
anonymous type in memory.
Syntax:
function()

// content to render.

- Anonymous function requiresa reference name to


access.
Syntax:
const f1 = function(){ };
- You can render the functional component into
Virtual DOM by using the reference as “element”
Syntax:
<f1 />
- DOM allows only an element, hence the functional
component is configured as element.

Note:
- The custom components must notcollide with
HTML DOM elements.
- The component name must notbe thesame as
HTML DOM element.
- Every component must follow “PascalCase or
lowercase” in naming.
- Lowercase is suggested only for elements in
browser.
- PascalCase is suggested forcomponent in React to
render in virtual DOM.
- Pascal Case: Every word first letter must bea
capital letter.
Ex:
App.js
const Titletext = () => <h2>WeIcome toReact JS</h2>;

ReactDOM.render(
<TitIetext />,
document.getEIementById('root')
Index.html
<!DOCTYPE htmI>
<htmI>
<head>
<titIe>HTML React App</title>
<script crossorigin
src=”https://unpkg.com/react@17/umd/react.develop
ment.js”></script>
<script crossorigin src="https://unpkg.com/react-
dom@17/umd/react-dom.development.js"></script>
<script crossorigin
src=”https://unpkg.com/@babeI/standalone/babeI.mi
n.js"></script>
<script type="text/jsx"
src=”../src/app.js"></script>
</head>
<body>
<div id="root/

</div>
</body>
</htmI>

Ex:
App.js
const titleText = ”User Login";
const Login = () => (

<h3 align="center">{titIeText}</h3>
<dI>
<dt>User Name</dt>
<dd><input type="text” cIassName="form-control"
/></dd>
<dt>Password</dt>
<dd><input type="password" cIassName="form-
control" /></dd>
</dI>
<button cIassName="btn btn-primary btn-
bIock">Login</button>

ReactDOM.render(
<Login />,
document.getEIementById('root')

Index.html
<!DOCTYPE htmI>
<htmI>
<head>
<titIe>HTML React App</title>
<Iink reI=”styIesheet"
href="https://cdn.jsdeIivr.net/npm/bootstrap@4.5.3/d
ist/css/bootstrap.min.css" integrity="sha384-
TX8t27EcRE3e/ihU7zmQxVncDAy5ulKz4rEkglXeMed4M
0jIfIDPvg6uqKI2xXr2" crossorigin="anonymous”>
<script crossorigin
srcm https://unpkg.com/react@17/umd/react.develop
ment.js”></script>
<script crossorigin src="https://unpkg.com/react-
dom@17/umd/react-dom.development.js"></script>
<script crossorigin
src=”https://unpkg.com/@babeI/standalone/babeI.mi
n.js"></script>
<script type="text/jsx"
y m E R
S C S C/app.js"></script>

<styIe>
div{
margin-top: 40px;
margin-left: 300px;
justify-content: center;
align-items: center;
padding: 10px;
border:2px solid darkcyan;
border-radius: 20px;
width: 300px;

</styIe>
</head>
<body>
<div id="root">

</div>
</body>
</htmI>
Class Components
- Components can be designed by using ES6 Classes
instead of Functions.
- Components designed with classes are known as
Class Components.
- Component is defined asa JavaScript Class that
extends “React.Component” base class.
Ex:
class Login -3' Not a component class

class Login extends React.Component -3'


Component class

- React.Component base class provides “render()”,


which you have to implement in your component
class.
Syntax:
class Login extends React.Component

render(){
return “JSX”;
- Class component is accessed and rendered as
element into Virtual DOM.
Syntax:
ReactDOM.render(
<Login />,
document.getEIementById('root')

Ex:
App.js
class Login extends React.Component

render(){
return(

<h3 aIign="center User Login</h3>


<dI>
<dt>User Name</dt>
<dd><input type="text” cIassName="form-control"
/></dd>
<dt>Password</dt>
<dd><input type="password" cIassName="form-
control / </dd>
</dI>
<button cIassName="btn btn-primary btn-
bIock">Login</button>

ReactDOM.render(
<Login />,
document.getEIementById('root')

Index.html
<!DOCTYPE htmI>
<htmI>
<head>
<titIe>HTML React App</title>
<Iink reI=”styIesheet"
href="https://cdn.jsdeIivr.net/npm/bootstrap@4.5.3/d
ist/css/bootstrap.min.css" integrity="sha384-
TX8t27EcRE3e/ihU7zmQxVncDAy5ulKz4rEkglXeMed4M
0jIfIDPvg6uqKI2xXr2 crossoriginm anonymous">
<script crossorigin
src=”https://unpkg.com/react@17/umd/react.develop
ment.js”></script>
<script crossorigin src="https://unpkg.com/react-
dom@17/umd/react-dom.development.js"></script>
<script crossorigin
src=”https://unpkg.com/@babeI/standalone/babeI.mi
n.js"></script>
<script type="text/jsx"
src=”../src/app.js"></script>
<styIe>
div{
margin-top: 40px;
margin-left: 300px;
justify-content: center;
align-items: center;
padding: 10px;
border:2px solid darkcyan;
border-radius: 20px;
width: 300px;
</styIe>
</head>
<body>
<div id="root)

</div>
</body>
</htmI>

Note: The data forclass component cancome from


Variable or Property
- Variable is immutable
- It is defined in module
- It is accessible directly by reference name.

- Property is mutable
- It is defined in class.
- It is accessible within the class by using “this”
keyword.

Ex:
App.js
var copyright = "copyright 2021”; // variable
class Login extends React.Component

heading = "User Login"; // property


render(){
return(

<h3 align="center”> {this.heading) </h3>


<dI>
<dt>User Name</dt>
<dd><input type="text” cIassName="form-control"
/></dd>
<dt>Password</dt>
<dd><input type="password" cIassName="form-
control / </dd>
</dI>
<button cIassName="btn btn-primary btn-
bIock">Login</button>
<p align="center"><i>{copyright}</i></p>
ReactDOM.render(
<Login />,
document.getEIementById(moot')

FAQ: Cana class component have function?


A.No. But it can havea function call.

Ex:
App.js
function template(){
return "React JS Class Component";

class Login extends React.Component

render(){
return <h2 aIign="center">{tempIate())</h2>;
ReactDOM.render(
<Login />,
document.getEIementById('root')

Functional Component vsClass Component


Functional Component
- Functional Components arereferred as “Stateless”
[dumb, presentational]
- Functional because they are designed usinga
JavaScript function.
- Stateless because they don't hold or manage state.
- It is difficult for transporting data from one
component toanother.
- It uses lot of round trips.
- It will be slow in access.
- It is more secured.
- It manages the memory.
- Tightly coupled.
- No easy to extend.
Class Component
- It is referred as “Stateful”
- Class of ES6
- It comprises of logic and data.
- It can hold and manage memory
- It is good fortransporting data across
components.
- It can have local state.
- It is not justa class buta container with
constructor, properties, methods, accessors.
- Loosely coupled.
- Easy to extend.
- Maintainability and Testability.

Properties in Component
[React Props]
- A component canaccept properties.
- So that component can customize the content that
it is going to return.
- It allows the component tochange the behaviour.
- You need properties to define behaviour for
component, which can change according to
situation and state.
- Props allows to customize the functionality of
component.
- All properties of react components areread-only.
- Property can't be modified [its name, structure]
but its value can change.

Properties in Functional Components:


- Functional components aredefined with
properties as parameters.
Syntax:
const hello = function(props){

props — can be any type: string, number, boolean,


object, array etc.
- The props of functional component areaccessed
by using attribute reference.
Syntax:
<heIIo propertyName=”{propertyVaIue}” />
- Every property passed intoa component have to
handle “Key and Value”
- Key refers to the property name
- Value refers to the value to store under specific
property name.
- The props that you define can handle any type of
data but ina “object” form.
Syntax:
const hello = obj => <h2> {obj.PropertyName} </h2>;
<heIIo PropertyName={‘VaIue’}/>

- Every property in react component is “Pure” type.


- Pure prop can't change its structure but can
change its value.
FAQ: What arePure properties in React?
- The properties of component areoften known as
Pure properties.
- They can't change according to state and situation
dynamically.

Ex:
App.js
const Product = obj =>(
<div classNamem card”>
<div className="card-header">
<h3>{obj.Name}</h3>
</div>
<div className="card-body">
<img src={obj.Photo} width="50%)l
height="300"></img>
</div>
<div className="card-footer">
<h4>{obj.Price}</h4>
</div>
</div>

ReactDOM.render(
<Product Name={'Nike Casuals’} Photo= shoe.jpg')
Price={4500.55}/>,
document.getEIementById(’root')

Index.html
<!DOCTYPE htmI>
<htmI>
<head>
<titIe>HTML React App</title>
<Iink reI=”styIesheet"
href="https://cdn.jsdeIivr.net/npm/bootstrap@4.5.3/d
ist/css/bootstrap.min.css" integrity="sha384-
TX8t27EcRE3e/ihU7zmQxVncDAy5ulKz4rEkglXeMed4M
0jIfIDPvg6uqKI2xXr2" crossorigin="anonymous”>
<script crossorigin
srcm https://unpkg.com/react@17/umd/react.develop
ment.js”></script>
<script crossorigin src="https://unpkg.com/react-
dom@17/umd/react-dom.development.js"></script>
<script crossorigin
src=”https://unpkg.com/@babeI/standalone/babeI.mi
n.js"></script>
<script type="text/jsx"
src=”../src/app.js"></script>
<styIe>

</styIe>
</head>
<body>
<div id="root">

</div>
</body>
</htmI>

Properties in class components:


- Class will not access props.
- Props are not passed as an argument into the
class.
- Properties are configured and accessed by using
“this” keyword.
- You have to createa dynamic object using “this”
keyword with properties.
Syntax:
this.PropertyName
- You can createa local property in class and access
by using “this” keyword.
- Properties can be defined with default values.
Ex:
App.js
class Product extends React.Component

Name = ”Nike Casuals";


Price = 4500.55;
Photo = "shoe.jpg";
render(){
return(
<div className="card">
<div className="card-header">
<h3>{this.Name}</h3>
</div>
<div className="card-body">
<img src={this.Photo) width=”50%l)
height="300"></img>
</div>
<div className="card-footer">
<h4>{this.Price}</h4>
</div>
</div>

ReactDOM.render(
<Product/>,
document.getEIementById('root')

Index.html
<!DOCTYPE htmI>
<htmI>
<head>
<titIe>HTML React App</title>
<Iink reI=”styIesheet"
href="https://cdn.jsdeIivr.net/npm/bootstrap@4.5.3/d
ist/css/bootstrap.min.css" integrity="sha384-
TX8t27EcRE3e/ihU7zmQxVncDAy5ulKz4rEkglXeMed4M
0jIfIDPvg6uqKI2xXr2" crossorigin="anonymous”>
<script crossorigin
src=”https://unpkg.com/react@17/umd/react.develop
ment.js”></script>
<script crossorigin src="https://unpkg.com/react-
dom@17/umd/react-dom.development.js"></script>
<script crossorigin
src=”https://unpkg.com/@babeI/standalone/babeI.mi
n.js"></script>
<script type="text/jsx"
src=”../src/app.js"></script>
<styIe>

</styIe>
</head>
<body>
<div id="root">

</div>
</body>
</htmI>
- In order to modify the property value of class you
need to createa “props” object for class.
Ex:
App.js
class Product extends React.Component

render(){
return(
<div className="card">
<div className="card-header">
<h3>{this.props.Name}</h3>
</div>
<div className="card-body">
<img src={this.props.Photo} width="50%"
height="300"></img>
</div>
<div className="card-footer">
<h4>{this.props.Price)</h4>
</div>
</div>

ReactDOM.render(
<Product Name={'Nike'} Photo={’shoe.jpg'}
Price={4500.56}/>,
document.getEIementById(moot')

Reusing the components with different values passed


into Props
- You can compose any component with another
component.
- This allows to reuse the existing components and
render in page.
Ex:
App.js
class Header extends React.Component

render(){
return(
<header cIassName="bg-danger text-white text-
center">
<h1>Amazon Shopping</h1>
</header>

class MenuContent extends React.Component

render(){
return(
<nav>

<Ii><span cIassName="fa fa-home"></span>


Home</li>
<Ii><span cIassName="fa fa-tv”></span>
Electronics</li>
<Ii><span cIassName="fa fa-beII"></span>
Fashion</li>
</uI>
</nav>

class Product extends React.Component

render(){
return(
<div cIassName="card
<div cIassName="card-header text-center">
<h3>{this.props.Name}</h3>
</div>
<div cIassName="card-body text-center”>
<img src={this.props.Photo} width="200"
height="200"></img>
</div>
<div cIassName="card-footer text-center”>
<h4>{this.props.Price)</h4>
</div>
</div>

class Products extends React.Component

render(){
return(
<div className="card-deck”>
<Product Name={’Nike Casuals’} Price={5600.66}
Photo={’shoe.jpg
<Product Name={’Lee Boot’} Price={4000.55}
Photo={’shoe1.jpg’}/>
<Product Name={’JBL Speaker’) Price={5000.55}
Photo={’speaker.jpg’}/>
</div>

class MainContent extends React.Component


render(){
return(

<Header />
<section>
<div className= row
<div className="coI-3">
<MenuContent />
</div>
<div className="coI-9">
<Products />
</div>
</div>
</section>
<footer className="text-center">
&copy; Copyright 2021;
</footer>
</>
ReactDOM.render(
<MainContent />,
document.getEIementById('root')

Index.html
<!DOCTYPE htmI>
<htmI>
<head>
<titIe>HTML React App</title>
<Iink reI=”styIesheet"
href="https://cdn.jsdeIivr.net/npm/bootstrap@4.5.3/d
ist/css/bootstrap.min.css" integrity="sha384-
TX8t27EcRE3e/ihU7zmQxVncDAy5ulKz4rEkglXeMed4M
0jIfIDPvg6uqKI2xXr2" crossorigin="anonymous”>
<Iink reI=”styIesheet"
href="https://stackpath.bootstrapcdn.com/font-
awesome/4.7.0/css/font-awesome.min.css"
crossorigin="anonymous">
<script crossorigin
srcm https://unpkg.com/react@17/umd/react.develop
ment.js”></script>
<script crossorigin src="https://unpkg.com/react-
dom@17/umd/react-dom.development.js"></script>
<script crossorigin
src=”https://unpkg.com/@babeI/standalone/babeI.mi
n.js"></script>
<script type="text/jsx"
src=”../src/app.js"></script>
<styIe>
section{
height: 600px;

footer{
background-color: maroon;
color:white;

ul{
list-style: none;
border:1px solid maroon;
background-color: maroon;
padding: 4px;
margin-top: 10px;
border-radius: 10px;
width: 200px;
color: white;
font-size: 30px;

</styIe>
</head>
<body>
<div id="root)

</div>
</body>
</htmI>
Task: Design the above example with functional
components
Ex:
App.js
const Nav = () =>
<navclassNamem)navbar navbar-expand-lg navbar-
dark bg-dark">
<button cIassName="navbar-toggIer"
type="button"
data-toggIe=”coIIapse"
data-target="#NavMenu">
<span className="navbar-toggIer-icon"></span>
</button>
<a href="#” className= navbar-branding
Amazon Shopping
</a>
<div cIassName="coIIapse navbar-collapse"
id=”NavMenu”>
<uIclassName="navbar-nav">
className="nav-item">
<a cIassName="nav-link" href="#”>Home</a>

className="nav-item">
<a cIassName="nav-link"
hrefm ’>EIectronics</a>

className="nav-item">
<a cIassName="nav-link"
href="#”>Footwear</a>

className="nav-item">
<a cIassName="nav-link" data-
toggIe="modaI" href="#Iogin">Login</a>
</Ii>
className="nav-item">
<SearchBox />

</div>
</nav>

const SearchBox = () =>


<divcIassName="input-groupÜ
<input type=”text” cIassName="form-control" />
<divclassNamem input-group-append">
<button cIassName="btn btn-warning
<span cIassName="fa fa-search"></span>
</button>
</div>
</div>

const Login = () =>


<div cIassName="modaI fade" id="Iogin">
<div className="modaI-diaIog">
<div className=”modaI-content”>
<div className="modaI-header">
<h3>User Login</h3>
</div>
<div className="modaI-body">
<dI>
<dt>User Name</dt>
<dd><input type=”text" cIassName="form-
control / </dd>
<dt>Password</dt>
<dd><input type=”password” cIassName="form-
control / </dd>
</dI>
</div>
<div className="modaI-footer">
<button cIassName="btn btn-
primary Login</button>
<button data-dismiss=”modaI" cIassName="btn
btn-danger”>CanceI</button>
</div>
</div>
</div>
</div>

class MainContent extends React.Component

render(){
return(

<Nav />
<Login />

ReactDOM.render(
<MainContent />,
document.getEIementById('root')

Index.html
<!DOCTYPE htmI>
<htmI>
<head>
<titIe>HTML React App</title>
<Iink reI=”styIesheet"
href="https://cdn.jsdeIivr.net/npm/bootstrap@4.5.3/d
ist/css/bootstrap.min.css" integrity="sha384-
TX8t27EcRE3e/ihU7zmQxVncDAy5ulKz4rEkglXeMed4M
0jIfIDPvg6uqKI2xXr2 crossoriginm anonymous”>
<Iink reI=”styIesheet"
href="https://stackpath.bootstrapcdn.com/font-
awesome/4.7.0/css/font-awesome.min.css"
CFossorigin="anonymous

<script crossorigin
src=”https://unpkg.com/react@17/umd/react.develop
ment.js”></script>
<script crossorigin src="https://unpkg.com/react-
dom@17/umd/react-dom.development.js </script>
<script crossorigin
src=”https://unpkg.com/@babeI/standalone/babeI.mi
n.js"></script>
<script src= https://code.jquery.com/jquery-
3.5.1.slim.min.js" integrity="sha384-
DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE
+IbbVYUew+OrCXaRkfj"
CFossorigin="anonymous
/SCript>

<script
srcm https://cdn.jsdeIivr.net/npm/bootstrap@4.5.3/dis
I/js/bootstrap.bundle.min.js" integrity="sha384-
ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7Rs
weNrtN/tE3MoK7ZeZDyx”
Crossorigin="anonymous
/SCript>
<script type="text/jsx"
y m E R
S C S C/app.js"></script>

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

</div>
</body>
</htmI>
Data in React Component
[Data-Driven Components]
- Data forcomponent comes froma service.
- JavaScript based libraries or frameworks usually
handle data by using
o Object
o Array
o Map
- Object: Representsa pseudo class with set of
properties and methods.
- Map: Representsa collection with key and value
references.
- Array: Representsa collection of values stored in
sequential order.

FAQ: What is difference between Map and Object?


Object Map
- Contains default keys - No default keys
- Can't know thecount - Can know thelength
of keys of count.
- Object requires an - Map is an iterator.
iterator to read keys
and value.

FAQ: What is Array.map()?


- It usesa call back function that createsa new array
with the result of any query.
Ex:
<script>
var products =[
{Name: "TV", Price: 45000.55},
{Name: "Mobile", Price: 33000.44},
{Name: "Shirt", Price: 3100.33}

function GetDetaiIs(product){
var details = [product.Name, product.Price].join("--
DII)+ IN<
br>”;

return details;

function PrintDetails(){
document.write(products.map(GetDetails));

PrintDetails();
</script>

Ex:
<script>
var products =[
{Name: "TV", Price: 45000.55},
{Name: "Mobile", Price: 33000.44},
{Name: "Shirt", Price: 3100.33}

function GetDetaiIs(product){
var details = ”g{product.Name) -
g{product.Pricej«br>”;
return details;
function PrintDetails(){
document.write(products.map(GetDetails));

PrintDetails();
</script>
Find()
Filter()
Ex:
<script>
var products =[
{Name: "TV", Price: 45000.55},
{Name: "Mobile", Price: 33000.44},
{Name: "Shirt", Price: 3100.33}

function GetDetaiIs(product){
return product.Price >= 30000;

function PrintDetails(){
var result = products.filter(GetDetails);
for(var item of result){
document.write(”g{item.Name) - g{item.Price)
<br>”);

PrintDetails();
</script>
React Component with Data
[Data Driven Component]
- Data forcomponent is provided by properties.
[props]
- In order to define data for any component you
have to configure properties.
- You can't directly use the local values of module.
- You can access data from local object of module or
from the property of another class by using
“aggregation” [Object-to-Object] communication.
[Has-A-Relation]
Ex:
App.js
var speaker ={
name: ’JBL Speaker’,
price: 6000.55,
photo: ’speaker.jpg’,
mdf: new Date()

class Category

CategoryName = ’Electronics'

class Product extends React.Component

product = speaker;
render(){
const category = new Category();
return(
<div className="card”>
<div className="card-header">
<h3>{this.product.name}</h3>
</div>
<div className="card-body">
<img src={this.product.photo} width="200"
height="200I
</div>
<div className="card-footer">
<h3>{this.product.price)</h3>
<p>{this.product.mdf.toLocaIeDateString())</p>
<p>{category.CategoryName}</p>
</div>
</div>

class MainContent extends React.Component

render(){
return(

<Product />
ReactDOM.render(
<MainContent />,
document.getEIementById(moot')

Index.html
<!DOCTYPE htmI>
<htmI>
<head>
<titIe>HTML React App</title>
<Iink reI=”styIesheet"
href="https://cdn.jsdeIivr.net/npm/bootstrap@4.5.3/d
ist/css/bootstrap.min.css" integrity="sha384-
TX8t27EcRE3e/ihU7zmQxVncDAy5ulKz4rEkglXeMed4M
0jIfIDPvg6uqKI2xXr2" crossorigin="anonymous”>
<Iink reI=”styIesheet"
href="https://stackpath.bootstrapcdn.com/font-
awesome/4.7.0/css/font-awesome.min.css"
crossorigin="anonymous">
<script crossorigin
srcm https://unpkg.com/react@17/umd/react.develop
ment.js”></script>
<script crossorigin src="https://unpkg.com/react-
dom@17/umd/react-dom.development.js"></script>
<script crossorigin
src=”https://unpkg.com/@babeI/standalone/babeI.mi
n.js"></script>
<script src="https://code.jquery.com/jquery-
3.5.1.slim.min.js" integrity="sha384-
DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE
+IbbVYUew+OrCXaRkf j
crossorigin="anonymous"></script>
<script
src=”https://cdn.jsdeIivr.net/npm/bootstrap@4.5.3/dis
I/js/bootstrap.bundle.min.js" integrity="sha384-
ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7Rs
weNrtN/tE3MoK7ZeZDyx”
crossorigin="anonymous"></script>
<script type="text/jsx"
src=”../src/app.js"></script>

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

</div>
</body>
</htmI>

Ex: Multi Level Hierarchy


App.js
class ProductDetails

name = ’JBL Speaker",


price = 5600.55;
photo = ’speaker.jpg’

class CategoryDetails extends ProductDetails

mdf = new Date(”2020-02-10");


CategoryName Electronics
class Product extends React.Component

render(){
const prod = new CategoryDetails();
return(
<div className="card”>
<div className="card-header">
<h3>{prod.name}</h3>
</div>
<div className="card-body">
<img src={prod.photo) width=”200" height="200"
/^
</div>
<div className="card-footer">
<h3>{prod.price)</h3>
<p>{prod.mdf.toLocaIeDateString())</p>
<p>{prod.CategoryName)</p>
</div>
</div>
class MainContent extends React.Component

render(){
return(

<Product />

ReactDOM.render(
<MainContent />,
document.getEIementById('root')

Index.html
<!DOCTYPE htmI>
<htmI>
<head>
<titIe>HTML React App</title>
<Iink reI=”styIesheet"
href="https://cdn.jsdeIivr.net/npm/bootstrap@4.5.3/d
ist/css/bootstrap.min.css" integrity="sha384-
TX8t27EcRE3e/ihU7zmQxVncDAy5ulKz4rEkglXeMed4M
0jIfIDPvg6uqKI2xXr2" crossorigin="anonymous”>
<Iink reI=”styIesheet"
href="https://stackpath.bootstrapcdn.com/font-
awesome/4.7.0/css/font-awesome.min.css"
crossorigin="anonymous">
<script crossorigin
srcm https://unpkg.com/react@17/umd/react.develop
ment.js”></script>
<script crossorigin src="https://unpkg.com/react-
dom@17/umd/react-dom.development.js"></script>
<script crossorigin
srcm https://unpkg.com/@babeI/standalone/babeI.mi
n.js"></script>
<script src="https://code.jquery.com/jquery-
3.5.1.slim.min.js integrity sha384-
DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE
+IbbVYUew+OrCXaRkf j
crossorigin="anonymous"></script>
<script
srcm https://cdn.jsdeIivr.net/npm/bootstrap@4.5.3/dis
I/js/bootstrap.bundle.min.js" integrity="sha384-
ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7Rs
weNrtN/tE3MoK7ZeZDyx”
crossorigin="anonymous"></script>
<SCf*ipt type= t£?Xt/jsx"
src=”../src/app.js"></script>

</head>
<body>
<div id= root

</div>
</body>
</htmI>
Presenting Collection
- Data collection is defined in JavaScript Array.
- It is an Array of Objects. [JSON]
- To return elements from an array, JavaScript
provides array functions
o tostring()
o join()
o filter()
o find()
o map()
Ex:
App.js
const products =[

name: BL Speaker",
price: 4500.55,
photo: 'speaker.jpg'

name: 'Nike Casuals',


price: 6000.55,
photo: 'shoe.jpg'

name: 'Shirt',
price: 2000.33,
photo: 'shirt.jpg'
name: 'Earpods’,
price: 4500.55,
photo: 'earpods.jpg’

class Product extends React.Component

productsData = products;
render(){
return(
<div className="card-deck">

this.productsData.map((product)=>{
return(
<div className="card”>
<div cIassName="card-header text-centering
<h3>(product.name)</h3>
</div>
<div cIassName="card-body text-center">
<img src={product.photo) width="200”
II I
height= 200

</div>
<div cIassName="card-footer text-center">
<h3>{product.price}</h3>
</div>
</div>

</div>

class MainContent extends React.Component

render(){
return(
<div className="container-fIuid">
<h1 className="text-center">Products
CataIog</h1>
<Product />
</div>

ReactDOM.render(
<MainContent />,
document.getEIementById(’root')

Index.html
<!DOCTYPE htmI>
<htmI>
<head>
<titIe>HTML React App</title>
<Iink reI=”styIesheet"
href="https://cdn.jsdeIivr.net/npm/bootstrap@4.5.3/d
ist/css/bootstrap.min.css" integrity="sha384-
TX8t27EcRE3e/ihU7zmQxVncDAy5ulKz4rEkglXeMed4M
0jIfIDPvg6uqKI2xXr2" crossorigin="anonymous”>
<Iink reI=”styIesheet"
href="https://stackpath.bootstrapcdn.com/font-
awesome/4.7.0/css/font-awesome.min.css"
CFossorigin="anonymous

<script crossorigin
srcm https://unpkg.com/react@17/umd/react.develop
ment.js”></script>
<script crossorigin src="https://unpkg.com/react-
dom@17/umd/react-dom.development.js </script>
<script crossorigin
src=”https://unpkg.com/@babeI/standalone/babeI.mi
n.js"></script>
<script src="https://code.jquery.com/jquery-
3.5.1.slim.min.js" integrity="sha384-
DfXdz2htPH0lsSSs5nCTpuj/zy4C+0GpamoFVy38MVBnE
+IbbVYUew+OrCXaRkf j
crossorigin="anonymous"></script>
<script
srcm https://cdn.jsdeIivr.net/npm/bootstrap@4.5.3/dis
I/js/bootstrap.bundle.min.js" integrity="sha384-
ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7Rs
weNrtN/tE3MoK7ZeZDyx”
CFossorigin="anonymous
/SCript>

<ScFipttype= t£?X t/jsx"


src=”../src/app.js"></script>

</head>
<body>
<div id= root

</div>
</body>
</htmI>

Ex:
App.js
const products =[

name: "JBL Speaker",


price: 4500.55,
photo: 'speaker.jpg'
name: 'Nike Casuals’,
price: 6000.55,
photo: 'shoe.jpg’

name: Shirt
price: 2000.33,
photo: 'shirt.jpg’

name: 'Earpods’,
price: 4500.55,
photo: 'earpods.jpg’

class Product extends React.Component

productsData = products;
render(){
return(
<tabIe cIassName="tabIe table-hovering
<thead>
<tr>
<th>Name</th>
<th>Price</th>
<th>Preview</th>
</tr>
</thead>
<tbody>

this.productsData.map((product)=>{
return(
<tr>

<td>{product.name)</td>
<td>{product.price)</td>
<td>
<img src={product.photo) width="100”
tI I
height= 100
</td>
</tr>

</tbody>
</tabIe>

class MainContent extends React.Component

render(){
return(
<div className="container-fIuid">
<h1 className="text-center">Products
CataIog</h1>
<Product />
</div>

ReactDOM.render(
<MainContent />,
document.getEIementById(’root')

Task:
const products =[

name: "JBL Speaker",


price: 4500.55,
photo: 'speaker.jpg',
description:[

Mfd Date(“2020-10-20”),
Features: “some description”
name: 'Nike Casuals',
price: 6000.55,
photo: 'shoe.jpg',
description:[

Mfd Date(“2020-10-20”),
Features: “some description”

name: 'Shirt',
price: 2000.33,
photo: 'shirt.jpg',
description:[
Mfd Date(“2020-10-20”),
Features: “some description”

name: 'Earpods',
price: 4500.55,
photo: 'earpods.jpg',
description:[

Mfd Date(“2020-10-20”),
Features: “some description”
State in React
- Web application uses “HTTP”
- HTTP isa state less protocol.
- It uses the mechanism “Go-Get-Forget”
GO : It establishes connection with server.
GET : It gets response forthe request.
FORGET: It cleans up everything. [Removes all
traces of current request]
- Stateless nature of HTTP is an advantage forweb
application, as it manages the memory.
- Stateless nature will be an issue for web
application that need continuous connection.
- Sharing information between components will be
difficult during runtime.
- State is an Object that holds some information
that is provided across multiple requests with
information changing according to situation.
- State uses
o Single Call
o Single Ton
- Single Ton: Object is created for the first request
and same object is used across multiple requests.
- Single Call: Object is created for every request
individually.
- State maintains object that contains information
provided to component across requests.
- In ReactJS functional components handle data in
properties they are state less.
- Class components arestateful
- React JS “Component” base class
[React.Component] providesa state object that
handle data forapplication.

What is difference between Props and State?


- Props are immutable
- Once you definea prop it can't be changed.
- State is mutable.
- It can change according to situation.

Rules for Configuring state in React JS application


- State object must be defined with an initial value.
- State must be initialized.
- It must be defined in initialization phase of
component.
- Initialization ina class component is defined using
“Constructor”
- Hence state is possible only in “Class Component”
notin functional component.
- State can't be changed explicitly.
- State can change its structure implicitly but can't
be modified explicitly.

Where thestate object is maintained forReact JS


application?
- Persistent State Object [Stored Permanently -
Cookie]
- In Memory state object [It is in browser memory —
Removed when browser is closed]

Configuring State for React JS component


- State in React JS is an object derived from
“React.Component” base class.
- You can createa component that implements
“React.Component” and allows access to state by
using “this” keyword.
Syntax:
this.state ={ }

class ComponentClass extends React.Component

constructor(){
//define the state object.

render(){}

- As per the rules of OOP in JavaScript the


constructor of derived class must havea super call.
- You can set state by using “this.setState()”
Syntax:
class ComponentClass extends React.Component

constructor(){
super();
//define the state object.

render(){)

Ex:
App.js
class Product extends React.Component

product ={
name: ’LGMobile',
price: 44000.44

constructor(){
super();
this.state ={
name: ’JBL Speaker',
price: 4500.55

render(){
return(
<dI>
<dt>Name</dt>
<dd>{this.state.name}</dd>
<dt>Price</dt>
<dd>{this.state.price}</dd>
<dt>MobiIe</dt>
<dd>{this.product.name}</dd>
<dt>Price</dt>
<dd>{this.product.price}</dd>
</dI>

class MainContent extends React.Component

render(){
return(
<div className="container-fIuid">
<Product />
</div>
ReactDOM.render(
<MainContent />,
document.getEIementById(’root')
)/

Add State to the component


Syntax:
class Product extends React.Component

constructor(props){
super(props);
this.state ={
data [

name: 'JBL Speaker',


price: 4500.44,
photo: 'speaker.jpg'
- Constructor is required to initialize the state.
- Constructor requires props as arguments to pass
into super class constructors.
- “props” are used as component properties.
Render Data from State
Ex
App.js
class Product extends React.Component

constructor(props){
super(props);
this.state ={
data [

name: 'JBL Speaker',


price: 4500.44,
photo: 'speaker.jpg'
render(){
return(
<div className="card">
<divclassNamem card-header
{this.state.data[0].name)
</div>
<div className="card-body">
<img src={this.state.data[0].photo}
width="200” height="200I
</div>
<div className="card-footer">
{this.state.data[0].price}
</div>
</div>
class MainContent extends React.Component

render(){
return(
<div className="container-fIuid">
<h2>Products CataIog</h2>
<Product />
</div>

ReactDOM.render(
<MainContent />,
document.getEIementById(’root')
)/

Ex: Multiple records in State


App.js
class Product extends React.Component
constructor(props){
super(props);
this.state ={
data [

name: 'JBL Speaker',


price: 4500.44,
photo: 'speaker.jpg'

name: 'Nike Casuals',


price: 5600.55,
photo: 'shoe.jpg'

render(){
return(
<div className="card-deck">

this.state.data.map((product)=>{
return(
<div className="card">
<div className= card-header">
{product.name)
</div>
<div className="card-body">
<img src={product.photo} width="200"
height="200” />
</div>
<div className="card-footer">
{product.price)
</div>
</div>

</div>
class MainContent extends React.Component

render(){
return(
<div className="container-fIuid">
<h2>Products CataIog</h2>
<Product />
</div>

ReactDOM.render(
<MainContent />,
document.getEIementById('root')
)/
Ex: Add and remove Array elements
class Product extends React.Component

constructor(props){
super(props);
this.state ={
data [

name: 'JBL Speaker',


price: 4500.44,
photo: 'speaker.jpg'

name: 'Nike Casuals


price: 5600.55,
photo: 'shoe.jpg'
this.state.data.push({name: 'Shirt', price:
1200.33, photo: ’shirt.jpg )
this.state.data.splice(1,1);

render(){
return(
<div className=”card-deck">

this.state.data.map((product)=>{
return(
<divclassNamem card
<div className= card-header
{product.name}
</div>
<div className="card-body">
<img src={product.photo} width="200"
height="200” />
</div>
<div className= card-footer
{product.price)
</div>
</div>

</div>

class MainContent extends React.Component

render(){
return(
<div className="container-fIuid">
<h2>Products CataIog</h2>
<Product />
</div>
ReactDOM.render(
<MainContent />,
document.getEIementById(’root')
)*

React JS PropTypes
- In real-time project we need to share our
component across applications and teams.
- We can use “props, state, life-cycle hooks, JSX,
PropTypes etc.”
- If data for component is coming from API
[Services] then the component must understand
and restrict the type of data.
- React JS uses “prop-types” object that handles
different types of data and also can restrict the
data.
- Alternative for “prop-types” is use a language that
can restrict the type. [Type Script]
- The prop-types are import into React JS
application to restrict the data type.
- React JS “PropTypes” are categorized into
following groups
Basic Types
Type Example Class
String "John", ‘John’, PropTypes.string
"John"
Number -10, 10, 3.4, 45.55 PropTypes.number
Boolean true/false PropTypes.bool
Symbol Symbol(“literal”) PropTypes.symbol
Object {Name: “TV”} PropTypes.object
Anything ‘John’, true, 10,{ ) PropTypes.node

Syntax:
Product.propTypes ={
Id: PropTypes.number,
Name: PropTypes.string,
Stock: PropTypes.bool
Description: PropTypes.node //any

Collection Types
Type Example Class
Array [] PropTypes.array
Array [10, 20, PropTypes.arrayOf([PropTypes.nu
of 30] mber])
Numb
ers
Enum [‘NotFou PropTypes.oneOfType([PropTypes
nd’, ‘Bad .number])
Request’]

Syntax:
Product.propTypes ={
Cities: PropTypes.array,
Products: PropTypes.arrayOf(PropTypes.string)

Object Types
Type Exampl Class
e
Object {name: PropTypes.object
‘TV’}
Numb {price: PropTypes.objectOf(PropTypes.nu
er 4500} mber)
Object
String {name: PropTypes.objectOf(PropType.strin
Object ‘TV’} g)

Syntax:
Product.propTypes ={
Details PropTypes.Object,
Price PropTypes.objectOf(PropTypes.number)

React Types
- It is used to define JSX type
- It is for configuring element type
Element <Product /> PropTypes.element

Requiring Types
- Requiring types are used forrestricting the values
by handling various validations.
Syntax:
Product.propTypes ={
Name: PropTypes.string.isRequired

Custom Types
- You can createa function or class to configurea
custom type
- You can use the custom type to restrict the value.
Syntax:
Product ={
Name: PropTypes.string
Price: PropTypes.number

Products.propTypes ={
TV: Product(Name, Price)

What is the Default Type?


- Object
How to define Union ofTypes?
- A property must allow multiple types but not all
types.
- You define union of types by using
“PropTypes.oneOfType([Type1, Type2])”

Ex:
App.js

const Product = (props) =>{


return(
<dI>
<dt>Product Code</dt>
<dd>{props.code}</dd>
<dt>Name</dt>
<dd>{props.name}</dd>
<dt>Price</dt>
<dd>{props.price}</dd>
<dt>Shipped To</dt>
<dd>

props.shippedTo.map((vaI)=>{
return(
<Ii key={vaI}>{vaI)</Ii>

</uI>
</dd>
</dI>
Product.propTypes ={
name: PropTypes.string,
price: PropTypes.number,
code: PropTypes.oneOfType([PropTypes.number,
PropTypes.string]),
shippedTo: PropTypes.arrayOf(PropTypes.string)

class MainContent extends React.Component

render(){
return(
<div className="container-fIuid">
<h2>Product DetaiIs</h2>
<Product code={’B101'} name={'Samsung TV’)
price={45000.55} shippedTo={[’DeIhi’,'Hyd ]y
</div>
ReactDOM.render(
<MainContent />,
document.getEIementById(moot')

Index.html
<!DOCTYPE htmI>
<htmI>
<head>
<titIe>HTML React App</title>
<Iink reI=”styIesheet"
href="https://cdn.jsdeIivr.net/npm/bootstrap@4.5.3/d
ist/css/bootstrap.min.css" integrity="sha384-
TX8t27EcRE3e/ihU7zmQxVncDAy5ulKz4rEkglXeMed4M
0jIfIDPvg6uqKI2xXr2" crossorigin="anonymous”>
<Iink reI=”styIesheet"
href="https://stackpath.bootstrapcdn.com/font-
awesome/4.7.0/css/font-awesome.min.css"
crossorigin="anonymous">
<script crossorigin
srcm https://unpkg.com/react@17/umd/react.develop
ment.js”></script>
<script crossorigin src="https://unpkg.com/react-
dom@17/umd/react-dom.development.js"></script>
<script
src--“https://cdnjs.cIoudfIare.com/ajax/libs/prop-
types/15.7.2/prop-types.js"integrity--“sha512-
Ttnt6nUh/1oV+4T/KWkG/0RvIIE0ZohMCT/GlzelxTce
olreR2A1r6zmgFnEvi7GgstoDblmpM0/Gi9CXKTqGQ--
--”crossorigin--”anonymous”></script>
<script crossorigin
src=”https://unpkg.com/@babeI/standalone/babeI.mi
j /S ript>

<script src="https://code.jquery.com/jquery-
3.5.1.slim.min.js" integrity="sha384-
DfXdz2htPH0lsSSs5nCTpuj/zy4C+0GpamoFVy38MVBnE
+IbbVYUew+OrCXaRkfj"
crossorigin="anonymous"></script>
<script
src=”https://cdn.jsdeIivr.net/npm/bootstrap@4.5.3/dis
I/js/bootstrap.bundle.min.js" integrity="sha384-
ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7Rs
weNrtN/tE3MoK7ZeZDyx”
crossorigin="anonymous"></script>
<script type="text/jsx"
S
y
C
m QS C/app.js </SCFipt>

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

</div>
</body>
</htmI>
Styles in React Application
- Styles provide attributes to make HTML more
interactive and responsive.
- Styles can be configured using
o Inline Styles
o Embedded Styles
o Cascading Style Sheets (CSS)
o Styling Libraries [Radium, React Materials]

Inline Styles
- Styles are defined for every element in component
individually by using “style” prop.
- You can pass any dynamic value into “style”
attribute so that it can change dynamically
according to state and situation.
Ex: JavaScript
<div id=”container” style=”background-color:red”>
document.getEIementById(“container”).style.backgrou
ndColor = “red”;
- React JS also uses “camel case” for configuring the
styles dynamically.
- Dynamic styles are defined by usinga style object.

Syntax: Applying styles using Style object


const styleobject ={
styleAttribute: ‘value’,
styleAttribute: ‘value

<div style={styIeObject)> </div>

Syntax: Apply attributes directly to element


<div style={ {attribute:value, attribute:value} \> </div>

Ex:
App.js
const headingstyle ={
backgroundColor: ’darkcyan',
color: 'white’,
textAlign: ’center’,
padding: ’Spx',
marginTop: '10px’

const Product = (props) =>{


return(
<dI>
<dt styIe={{backgroundCoIor: ’gray', color:
’white’}}>Product Code</dt>
<dd>{props.code}</dd>
<dt>Name</dt>
<dd>{props.name}</dd>
<dt>Price</dt>
<dd>{props.price}</dd>
<dt>Shipped To</dt>
<dd>
props.shippedTo.map((vaI)=>{
return(
<Ii key={vaI}>{vaI)</Ii>

</uI>
</dd>
</dI>

Product.propTypes ={
name: PropTypes.string,
price: PropTypes.number,
code: PropTypes.oneOfType([PropTypes.number,
PropTypes.string]),
shippedTo: PropTypes.array0f(PropTypes.string)
class MainContent extends React.Component

render(){
return(
<div className="container-fIuid">
<h2 style={headingStyIe)>Product DetaiIs</h2>
<Product code={’B101'} name={'Samsung TV’)
price={45000.55} shippedTo={[’DeIhi’,'Hyd
</div>

ReactDOM.render(
<MainContent />,
document.getEIementById('root')

Embedded Styles
- Embedded styles are defined in “HTML” page by
using <styIe> element.
- It can embeda setofstyles, which are allowed to
reuse across elements.
Index.html
<styIe>
dt{
background-color: gray;
color:white;
padding:5px;

</styIe>
CSS
- Styles are maintained ina separate CSS file and are
linked to your document.
- You can also import CSS files into component and
use.
- If you are usinga modular system forreact
application then you have to import the CSS files
into component.
Syntax:
app.css
selector{
attribute: value

app.js
import “./app.css”
- If you are not usinga modular system then you
have to link all your CSS files into index.html
<Iink reI=”styIesheet” href=”../src/app.css”>

Note: You can also use “less and Sass” for CSS.

Events and Interactions


What is Event?
- Event isa message sent by sender to its subscriber
in order to notify the change.
- Event follows “Observer”, which isa
communication design pattern.
- Event uses “Delegate mechanism” — Function
Pointer.
JavaScript
function SubmitClick()

<button onclick="SubmitCIick()"> Submit </button>


Event Handler

- React JS uses all JavaScript browser events in the


same way.
- Events are defined in “Camel Case”.
- Event handler uses function pointer as “JSX
expression”
React JS
function SubmitClick()

<button onClick=(SubmitCIick)> Submit </button>


Event Handler
- Sender notified the changes.
- Subscriber comprises of actions to perform.

- React JS can use all JavaScript Browser events,


which includes
o Clipboard Events
o Composition Events
o Keyboard Events
o Focus Events
o Generic Events
o Mouse Events
o Pointer Events
o Selection Events
o Touch Events
o UI Events
o Wheel Events
o Media Events
o Image Events
o Animation Events
o Transition Events
o Timer Events etc.
- Java Script events have2 arguments
o this : Sends information about the object
[related properties and methods]
o event : Sends information about the event[
related properties and methods]

- React JS events have only “event” argument. [You


can't use this as argument].
- Object related properties can be accessed by using
“event.target” object.
Ex: Event in Functional Component
App.js
function Product(){
function InsertClick(){
alert(”Record Inserted");

return(
<div>
<button onCIick={InsertCIick} name="btnInsert"
cIassName="btn btn-primary">Insert</button>
</div>
class MainContent extends React.Component

render(){
return(
<div className="container-fIuid">
<h3>Event HandIing</h3>
<Product />
</div>

ReactDOM.render(
<MainContent />,
document.getEIementById(moot')

Ex: Event Argument [event]

App.js
function Product(){
function InsertCIick(e){
alert(”You Clicked AtX Position ${e.cIientX}\n Button
Class Name=${e.target.className}”);

return(
<div>
<button onCIick={InsertCIick} name="btnInsert"
cIassName="btn btn-primary">Insert</button>
</div>

class MainContent extends React.Component

render(){
return(
<div className="container-fIuid">
<h3>Event HandIing</h3>
<Product />
</div>
ReactDOM.render(
<MainContent />,
document.getEIementById (moot')

Events in Class Component


- In Class component events actions are defined as
Methods.
- Event handler points towards specific method.

Ex:
App.js
class Product extends React.Component

InsertCIick(e){
alert(”X Position: ${e.cIientX}\nName:
${e.target.name)”);
render(){
return(
<div>
<button name="btnInsert"
onClick={this.InsertClick) cIassName="btn btn-
primary">Insert</button>
</div>

class MainContent extends React.Component

render(){
return(
<div className="container-fIuid">
<h3>Event HandIing</h3>
<Product />
</div>
ReactDOM.render(
<MainContent />,
document.getEIementById('root')

Index.html
<!DOCTYPE htmI>
<htmI>
<head>
<titIe>HTML React App</title>
<Iink reI=”styIesheet"
href="https://cdn.jsdeIivr.net/npm/bootstrap@4.5.3/d
ist/css/bootstrap.min.css" integrity="sha384-
TX8t27EcRE3e/ihU7zmQxVncDAy5ulKz4rEkglXeMed4M
0jIfIDPvg6uqKI2xXr2" crossorigin="anonymous">
<Iink reI=”styIesheet"
href="https://stackpath.bootstrapcdn.com/font-
awesome/4.7.0/css/font-awesome.min.css"
crossorigin="anonymous">
<Iink reI=”styIesheet" href="../src/app.css”>
<script crossorigin
srcm https://unpkg.com/react@17/umd/react.develop
ment.js”></script>
<script crossorigin src="https://unpkg.com/react-
dom@17/umd/react-dom.development.js"></script>
<script
src=”https://cdnjs.cIoudfIare.com/ajax/libs/prop-
types/15.7.2/prop-types.js" integrity=”sha512-
Ttnt6nUh/1oV+4T/KWkG/ORvIIEOZohMCT/GlzelxTceol
reR2A1r6zmgFnEvi7GgstoDblmpMO/Gi9CXKTqGQ=="
crossorigin="anonymous"></script>
<script crossorigin
src=”https://unpkg.com/@babeI/standalone/babeI.mi
j /S ript>

<script src="https://code.jquery.com/jquery-
3.5.1.slim.min.js" integrity="sha384-
DfXdz2htPH0lsSSs5nCTpuj/zy4C+0GpamoFVy38MVBnE
+IbbVYUew+OrCXaRkfj"
crossorigin="anonymous"></script>
<script
src=”https://cdn.jsdeIivr.net/npm/bootstrap@4.5.3/dis
I/js/bootstrap.bundle.min.js" integrity="sha384-
ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7Rs
weNrtN/tE3MoK7ZeZDyx”
crossorigin="anonymous"></script>
<script type="text/jsx"
y m E R
S C S C/app.js"></script>

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

</div>
</body>
</htmI>

Event Handler
- Event handler isa function pointer.
- Multiple controls can use the same function to
handle various functionalities.

Ex:
App.js

class Product extends React.Component


DataOperations(e){
switch(e.target.value)

case "Insert”:
alert("Record Inserted");
break;
case "Update
alert("Record Updated");
break;
case "Delete":
alert("Record Deleted”);
break;

render(){
return(
<div>
<div className="btn-group">
<button name=”btnInsert" vaIue="Insert"
onClick={this.Dataoperations) cIassName="btn btn-
primary">Insert</button>
<button name=”btnUpdate" vaIue="Update"
onClick={this.Dataoperations) cIassName="btn btn-
success">Update</button>
<button name="btnDeIete vaIue="DeIete”
onClick={this.Dataoperations) cIassName="btn btn-
danger”>DeIete</button>
</div>
<h2 aIign="center </h2>
</div>

class MainContent extends React.Component

render(){
return(
<div className="container-fIuid">
<h3>Event HandIing</h3>
<Product />
</div>
ReactDOM.render(
<MainContent />,
document.getEIementById (moot')

Note: State defined fora component is initialized into


component memory.
The methods configured with event handler
must bind with the component memory.
Syntax:
{this.buttonCIick.bind(this)}

Using State in React User Interactions


[Define State and Set State on Event Handling]
- State is required to configure ina component in
order to store the data and use between
interactions.
- Properties are read-only and will not allow to set
value.
- Hence state is required to configure value
dynamically.
- State is initialized
Syntax:
this.state ={
property: “value”

- You can modify the state by using “setstate()”


Syntax:
this.setState(function(state){
property: state.property = “New Value”

- Events can't access current state. You have to bind


the current context to event.
- If event has to use any of the component related
properties and methods then you have to bind
with current context.
Syntax:
this.eventHandIerName.bind(this)
- You can bind in the initialization phase.
Syntax:
constructor(props)

super();
this.state ={ );
this.eventHandIer
this.eventHandler.bind(this);

- You can bind at the event handler while


configuring event for DOM element.
Syntax:
<button onClick={this.eventHandIer.bind(this)}>
Text </button>

Ex:
App.js
class Product extends React.Component

constructor(props){
super(props);
this.state ={
msg: ”Select Database Commander

this.InsertCIick = this.InsertCIick.bind(this);
this.UpdateCIick = this.UpdateCIick.bind(this);
this.DeIeteCIick = this.DeIeteCIick.bind(this);

InsertClick(){
this.setState(state=>({
msg: state.msg = "Record Inserted"
I)):

UpdateClick(){
this.setState(state=>({
msg: state.msg = "Record Updated"
I)):

DeleteClick(){
this.setState(state=>({
msg: state.msg = "Record Deleted Successfully.."
I)):

render(){
return(
<div className="btn-group">
<button onClick={this.InsertClick) cIassName="btn
btn-primary">Insert</button>
<button onClick=(this.UpdateClick)
cIassName="btn btn-success">Update</button>
<button onClick={this.DeleteClick} className= btn
btn-danger”>DeIete</button>
</div>
<h2 cIassName="text-center”>{this.state.msg}</h2>

class MainContent extends React.Component

render(){
return(
<div className="container-fIuid">
<h3>Event HandIing</h3>
<Product />
</div>

ReactDOM.render(
<MainContent />,
document.getEIementById('root')

Index.html
<!DOCTYPE htmI>
<htmI>
<head>
<titIe>HTML React App</title>
<Iink reI=”styIesheet"
href="https://cdn.jsdeIivr.net/npm/bootstrap@4.5.3/d
ist/css/bootstrap.min.css" integrity="sha384-
TX8t27EcRE3e/ihU7zmQxVncDAy5ulKz4rEkglXeMed4M
0jIfIDPvg6uqKI2xXr2 crossoriginm anonymous”>
<Iink reI=”styIesheet"
href="https://stackpath.bootstrapcdn.com/font-
awesome/4.7.0/css/font-awesome.min.css"
CFossorigin="anonymous

<Iink reI=”styIesheet" href="../src/app.css">


<script crossorigin
src=”https://unpkg.com/react@17/umd/react.develop
ment.js”></script>
<script crossorigin src="https://unpkg.com/react-
dom@17/umd/react-dom.development.js"></script>
<script
src=”https://cdnjs.cIoudfIare.com/ajax/libs/prop-
types/15.7.2/prop-types.js" integrity=”sha512-
Ttnt6nUh/1oV+4T/KWkG/ORvIIEOZohMCT/GlzelxTceol
reR2A1r6zmgFnEvi7GgstoDblmpMO/Gi9CXKTqGQ=="
crossorigin="anonymous"></script>
<script crossorigin
src=”https://unpkg.com/@babeI/standalone/babeI.mi
n
jS /SCript>

<script src="https://code.jquery.com/jquery-
3.5.1.slim.min.js" integrity="sha384-
DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE
+IbbVYUew+OrCXaRkfj"
CFossorigin="anonymous
/SCript>
<script
srcm https://cdn.jsdeIivr.net/npm/bootstrap@4.5.3/dis
I/js/bootstrap.bundle.min.js" integrity="sha384-
ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7Rs
weNrtN/tE3MoK7ZeZDyx”
crossorigin="anonymous"></script>
<ScFipttype= t£?Xt/jsx"
src=”../src/app.js"></script>
</head>
<body>
<div id="root">

</div>
</body>
</htmI>

Ex: Instead on using multiple methods you can use


single method to handle all interactions.
App.js
class Product extends React.Component

constructor(props){
super(props);
this.state ={
msg: "Select Database Command"

this.DatabaseOperations =
this.DatabaseOperations.bind(this);

DatabaseOperations(e)

switch(e.target.value)

Case"Insert
ing

this.setState(state=>({
msg : state.msg = ”Record Inserted"

break;
case "Update":
this.setState(state=>({
msg : state.msg = "Record Updated"
break;
case "Delete":
this.setState(state=>({
msg : state.msg = ”Record Deleted"

break;

render(){
return(

<div className="btn-group">
<button vaIue=”Insert"
onClick={this.Databaseoperations} cIassName="btn
btn-primary">Insert</button>
<button vaIue=”Update
onClick={this.Databaseoperations) cIassName="btn
btn-success">Update</button>
<button vaIue=”DeIete
onClick={this.Databaseoperations} cIassName="btn
btn-danger”>DeIete</button>
</div>
<h2 cIassName="text-center”>{this.state.msg}</h2>

class MainContent extends React.Component

render(){
return(
<div className="container-fIuid">
<h3>Event HandIing</h3>
<Product />
</div>

ReactDOM.render(
<MainContent />,
document.getEIementById('root')

FAQ: What arethevarious event binding techniques


used foraccessing the current component members?
- You can bind the event in initialization phase of
component “constructor()”
- You can bind the event in “event handler”of DOM
element.
- You can bind the event without using “bind()”
method, you have tousesa call back technique to
return the event and bind to element.
- You can use the event return value and bind to
event by using anonymous technique.
Ex: Constructor
App.js
class Product extends React.Component

constructor(props){
super(props);
this.state ={
msg : 'Select Database Operation'
this.InsertCIick = this.InsertCIick.bind(this);

InsertClick(){
this.setState({
msg: 'Record Inserted'

render(){
return(

<div className="btn-group">
<button onClick={this.InsertClick) cIassName="btn
btn-primary">Insert</button>
</div>
<h2 cIassName="text-center”>{this.state.msg}</h2>
class MainContent extends React.Component

render(){
return(
<div className="container-fIuid">
<h3>Event HandIing</h3>
<Product />
</div>

ReactDOM.render(
<MainContent />,
document.getEIementById('root')

Ex: DOM Event Handler


App.js
class Product extends React.Component

constructor(props){
super(props);
this.state ={
msg # Select Database Operation

InsertClick(){
this.setState({
msg: 'Record Inserted'

render(){
return(

<div className="btn-group">
<button onClick={this.InsertCIick.bind(this))
cIassName="btn btn-primary Insert</button>
</div>
<h2 cIassName="text-center”>{this.state.msg}</h2>

class MainContent extends React.Component

render(){
return(
<div className="container-fIuid">
<h3>Event HandIing</h3>
<Product />
</div>
ReactDOM.render(
<MainContent />,
document.getEIementById('root')

Ex:Without bind() method


class Product extends React.Component

constructor(props){
super(props);
this.state ={
msg : 'Select Database Operation'

InsertClick(){
this.setState({
msg: 'Record Inserted'
render(){
return(

<div className="btn-group">
<button onClick={()=> this.InsertCIick())
cIassName="btn btn-primary">Insert</button>
</div>
<h2 cIassName="text-center”>{this.state.msg}</h2>

class MainContent extends React.Component

render(){
return(
<div className="container-fIuid">
<h3>Event HandIing</h3>
<Product />
</div>

ReactDOM.render(
<MainContent />,
document.getEIementById('root')

Ex: Anonymous
App.js
class Product extends React.Component

constructor(props){
super(props);
this.state ={
msg : 'Select Database Operation'
InsertClick = ()=>{
this.setState({
msg: 'Record Inserted'

render(){
return(

<div className="btn-group">
<button onClick={this.InsertClick) cIassName="btn
btn-primary">Insert</button>
</div>
<h2 cIassName="text-center”>{this.state.msg}</h2>
class MainContent extends React.Component

render(){
return(
<div className="container-fIuid">
<h3>Event HandIing</h3>
<Product />
</div>

ReactDOM.render(
<MainContent />,
document.getEIementById('root')
FAQ: What arecontrolled and uncontrolled
components?
- Uncontrolled component: It handles the events by
using basic DOM manipulations, It doesn't require
any event binding.
- Controller Component: It handles the events by
using its internal state. It requires event binding.

Ex: Uncontrolled Component [No-State defined]


App.js
class Product extends React.Component

InsertClick(){
document.write("Record Inserted");

render(){
return(

<div className="btn-group">
<button onClick={this.InsertClick) cIassName="btn
btn-primary >Insert</button>
</div>
<h2 cIassName="text-center”></h2>

class MainContent extends React.Component

render(){
return(
<div className="container-fIuid">
<h3>Event HandIing</h3>
<Product />
</div>
ReactDOM.render(
<MainContent />,
document.getEIementById('root')

Note: React can use all browser events forelements,


which require event binding based on the component
type. [Controlled Components require - Event
Binding]

Ex: Uncontrolled Component using “onChange”


App.js
class Product extends React.Component

CityChanged(e){
document.write(”Selected City: ${e.target.value}”);

render(){
return(
<div className="btn-group">
<seIect onChange={this.CityChanged}
className="form-controI”>
<option>DeIhi</option>
<option>Hyd</option>
<option>Chennai</option>
</seIect>
</div>
<h2 cIassName="text-center”></h2>

class MainContent extends React.Component

render(){
return(
<div className="container-fIuid">
<h3>Event HandIing</h3>
<Product />
</div>

ReactDOM.render(
<MainContent />,
document.getEIementById('root')

FAQ: How you can manage cross-browser


compatibility while working with events in “React.js”?
A: React.js manages thecross-browser compatibility by
using “SyntheticEvent”.

SyntheticEvent
- SyntheticEvent isa part of React.js Event Handling.
- It is responsible for making the react event
compatible with “cross-browser”.
- Events can work identically across all browsers.
- The event argument “event" is managed by
SyntheticEvent object of React.js
- It is responsible for making the event native for
specific browser.
Ex: Get all properties of SyntheticEvent
App.js
class Register extends React.Component

RegisterCIick(SyntheticEvent){
for(var property in SyntheticEvent)

document.write(property+ "<br>");

render(){
return(

<button vaIue=”Register"
onClick={this.RegisterCIick)>Register</button>
class MainContent extends React.Component

render(){
return(
<div className="container-fIuid">
<h3>Event HandIing</h3>
<Register/>
</div>

ReactDOM.render(
<MainContent />,
document.getEIementById (moot')
- Every SyntheticEvent object comprises of
following attribute
bubbles Boolean
cancelable Boolean
isTrusted Boolean
target DOMEventTarget
type String
preventDefault() Void
stopPropagation( Void

persist() Void
nativeEvent DOMEvent

- You can access the browser native event related


details by using “nativeEvent”

Keyboard Events
React uses Keyboard events to handle various
interactions with regard to key code, and key
actions.
- onKeyDown : Indicates the actions to perform
on key down
- onKeyUp - Indicates actions to perform on
keyup.
- onKeyPress : Indicates actions to perform
when user finisha key and uses another key.

Properties:
- keyCode
- charCode
- shiftKey
- ctrlKey
- which
- key [Return the key used]

Ex: Identifying the Key used


App.js
class Register extends React.Component

constructor(props){
super(props);
this.state ={
msg:"

this.VerifyPassword = this.VerifyPassword.bind(this);
VerifyPassword(e){
if(e.key ”CapsLock"){
this.setState({
msg: ’Caps Lock ON’

) else{
this.setState({
+* 8*"

render(){
return(

<div>
<IabIe>Password</IabIe>
<div>
<input onKeyUp={this.VerifyPassword)
type="password" className= orm-control" />
<span>{this.state.msg)</span>
</div>
</div>

class MainContent extends React.Component

render(){
return(
<div className="container-fIuid">
<h3>Event HandIing</h3>
<Register />
</div>
ReactDOM.render(
<MainContent />,
document.getEIementById('root')

Ex: Actions on specific key handling


class Register extends React.Component

VerifyChar(e){
if(e.key=="y”){
location.href=”http://www.amazon.in”;
) else{
document.write("Action Canceled..");

render(){
return(

<input onKeyUp={this.VerifyChar) type="text”


pIacehoIder="Y to Continue andN to Stolid
class MainContent extends React.Component

render(){
return(
<div className="container-fIuid">
<h3>Event HandIing</h3>
<Register />
</div>

ReactDOM.render(
<MainContent />,
document.getEIementById('root')

Ex: Verify Value entered in input element on Key


Event
App.js
class Register extends React.Component

constructor(props){
super(props);
this.state ={
users:[
{UserName: 'john’),
{UserName: ’john1'),
{UserName: ’david’),
{UserName: ’david_nit')

msg:”

this.VerifyUser = this.VerifyUser.bind(this);
VerifyUser(e){
for(var user of this.state.users)

if(user.UserName==e.target.value)

this.setState({
msg: 'User Name Taken - Try Another’

break;
) else{
this.setState({
msg: ’User Name Available’

render(){
return(
<div>
<IabeI>User Name</IabeI>
<div>
<input onKeyUp={this.VerifyUser) type="text"
cIassName="form-control” />
<span>{this.state.msg}</span>
</div>
</div>

class MainContent extends React.Component

render(){
return(
<div className="container-fIuid">
<h3>Event HandIing</h3>
<Register/>
</div>

ReactDOM.render(
<MainContent />,
document.getEIementById('root')

Ex: Verify User Name andPassword


App.js
class Register extends React.Component

constructor(props){
super(props);
this.state ={
users:[
{UserName: ’john’),
{UserName: 'john1'),
{UserName: 'david’),
{UserName: ’david_nit')

msg: ”,
regExp: /(?=.*[A-Z])\w{4,15}/,
pwdMsgt

this.VerifyUser = this.VerifyUser.bind(this);
this.VerifyPassword = this.VerifyPassword.bind(this);

VerifyUser(e){
for(var user of this.state.users)

if(user.UserName==e.target.value)

this.setState({
msg: 'User Name Taken - Try Another

break;
) else{
this.setState({
msg: 'User Name Available'

VerifyPassword(e){
if(e.target.value.match(this.state.regExp)){
this.setState({
pwdMsg: 'Strong Password'

} else{
if(e.target.value.Iength<4){
this.setState({
pwdMsg: 'Poor Password'

) else{
this.setState({
pwdMsg: 'Weak Password'
render(){
return(

<div className="form-group">
<IabeI>User Name</IabeI>
<div>
<input onKeyUp={this.VerifyUser) type="text"
cIassName="form-control” />
<span>{this.state.msg}</span>
</div>
</div>
<div className="form-group">
<IabeI>Password</IabeI>
<div>
<input onKeyUp={this.VerifyPassword}
type="password" cIassName="form-control" />
<span>{this.state.pwdMsg}</span>
</div>
</div>

class MainContent extends React.Component

render(){
return(
<div className="container-fIuid">
<h3>Event HandIing</h3>
<Register />
</div>
ReactDOM.render(
<MainContent />,
document.getEIementById('root')

Mouse Events
Mouse events specifies actions to perform with
regard to mouse interactions on web page or app.
- onClick
- onContextMenu
- onDoubleClick
- onDrag
- onDragEnd
- onDragEnter
- onDargExit
- onMouseDown
- onMouseEnter
- onMouseMove
- onMouseLeave
- onMouseover etc.
Properties
- altKey
- button
- clientX
- clientY etc..
Ex: onMouseover, onMouseLeave (onmouseout)
App.js
class MouseDemo extends React.Component

constructor(props)(
super(props);
this.state ={
styleobj:{
color: 'black’

this.GetCoIor = this.GetCoIor.bind(this);
this.SetDefauItCoIor =
this.SetDefauItCoIor.bind(this);

GetCoIor(e){
switch(e.target.id){
case "red":
this.setState({
styleobj:{
color: ’red'

break;
Cãse"green
est

this.setState({
style0bj:{
color: ’green'

break;
case "blue":
this.setState({
styleobj:{
color: ’blue'

break;
SetDefaultColor()(
this.setState({
styleobj:{
color:’black’

render(){
return(

<div onMouseover={this.GetColor}
onMouseLeave={this.SetDefaultColor) cIassName="row
mr-5">
<div cIassName="coI" id=”red” cIassName="bg-
danger”>
Red color
</div>
<div cIassName="coI" id=”green” cIassName="bg-
SLJccess

Green color
</div>
<div cIassName="coI” id="bIue" cIassName="bg-
info">
Blue color
</div>
</div>
<h1 style={this.state.styIeObj}>SampIe Text</h1>

class MainContent extends React.Component

render(){
return(
<div className="container-fIuid">
<h3>Event HandIing</h3>
<MouseDemo />
</div>

ReactDOM.render(
<MainContent />,
document.getEIementById(’root')

Ex: Accessing the mouse pointier position on


mousemove
App.js
class MouseDemo extends React.Component

constructor(props){
super(props);
this.state ={
styleobj {
position: ",
left:"
top:”

this.GetMousePosition =
this.GetMousePosition.bind(this);

GetMousePosition(e){
this.setState({
styleobj:(
position: ’fixed’,
left: e.cIientX+ ’px',
top: e.cIientY+ ’px'

render(){
return(

<div onMouseMove={this.GetMousePosition)>
<div style={{height:’1000px’}}>
</div>
<img style={this.state.styleobj} src="fIag.gif"
height="50" width="50"/>
</div>

class MainContent extends React.Component

render(){
return(
<div className="container-fIuid">
<h3>Event HandIing</h3>
<MouseDemo />
</div>
ReactDOM.render(
<MainContent />,
document.getEIementById(moot')

Ex: Controlling Animations on Mouse Event


App.js

class MouseDemo extends React.Component

StartScroIIing(e){
e.target.start();

StopScroIIing(e){
e.target.stop();

render(){
return(

<div>
<marquee onMouseLeave={this.StartScrolling}
onMouseover={this.StopScrolling} scrollamount="10">
<img src="speaker.jpg" width="100"
height=II100I
<imgsrcm shirt.jpg" width="100 height="100”

<img src="earpods.jpg" width="100"


height=II100I
<img src="shoe.jpg” width="100” height=”100”

<img src="jeans.jpg” width="100” height=”100”

</marquee>
</div>
class MainContent extends React.Component

render(){
return(
<div className="container-fIuid">
<h3>Event HandIing</h3>
<MouseDemo />
</div>

ReactDOM.render(
<MainContent />,
document.getEIementById('root')

Ex: onChange Event


App.js
class EventsDemo extends React.Component

constructor(props){
super(props);
this.state ={
msg: 'Selecta City’

this.CityChanged = this.CityChanged.bind(this);

CityChanged(e){
this.setState({
msg: e.target.value

render(){
return(

<div>
<IabeI>SeIect City</IabeI>
<div>
<seIect onChange={this.CityChanged\>
<option>SeIect Your City</option>
<option>DeIhi</option>
<option>Hyd</option>
<option>Chennai</option>
</seIect>
</div>
</div>
<h3 align="center”>City Name
{this.state.msg)</h3>

class MainContent extends React.Component

render(){
return(
<div className="container-fIuid">
<h3>Event HandIing</h3>
<EventsDemo />
</div>

ReactDOM.render(
<MainContent />,
document.getEIementById('root')

onBlur, onFocus, onselect, onCut, onCopy, onPaste,


onDoubleClick, onContextMenu

Ex:Double Click Native is “ondblclick” -


SyntenticEvent “onDoubleClick”
class EventsDemo extends React.Component

constructor(props){
super(props);
this.state ={
msg: 'Selecta City’

this.CityChanged = this.CityChanged.bind(this);

CityChanged(e){
this.setState({
msg: e.target.value

Openlmage(){
window.open('shoe.jpg’,’Nike','Width=400
height=500');

render(){
return(

<div>
<img onDoubleClick={this.Openlmage}
srcm shoe.jpg idth=”40 height=”40I
<p>DoubIe Click to View Large</p>
</div>
<div>
<IabeI>SeIect City</IabeI>
<div>
<seIect onChange={this.CityChanged}>
<option>SeIect Your City</option>
<option>DeIhi</options
<option>Hyd</option>
<option>Chennai</option>
</seIect>
</div>
</div>
<h3 align="center”>City Name
{this.state.msg)</h3>

class MainContent extends React.Component


render(){
return(
<div className="container-fIuid">
<h3>Event HandIing</h3>
<EventsDemo />
</div>

ReactDOM.render(
<MainContent />,
document.getEIementById('root')

onsubmit
- It is the event configured for “form” element.
- It fires up the functionality when form is
submitted.
Ex:
App.js
class EventsDemo extends React.Component

SubmitCIick(e){
alert(”Name=${e.target[0].value}\nMobiIe=${e.target[1
].value}”)

render(){
return(

<form onsubmit={this.SubmitCIick}>
<dI>
<dt>User Name</dt>
<dd><input type="text" name="username"
/></dd>
<dt>MobiIe</dt>
<dd>
<input type="text" name="mobiIe" />
</dd>
</dI>
<button>Submit</button>
</form>
class MainContent extends React.Component

render(){
return(
<div className="container-fIuid">
<h3>Event HandIing</h3>
<EventsDemo />
</div>

ReactDOM.render(
<MainContent />,
document.getEIementById('root')

Ex: Reading all element values

class EventsDemo extends React.Component

SubmitCIick(e){
for(var element ofe.target){
document.write(element.value+ "<br>");

render(){
return(

<form onsubmit={this.SubmitCIick}>
<dI>
<dt>User Name</dt>
<dd><input type="text" name="username"
/></dd>
<dt>MobiIe</dt>
<dd>
<input type="text" name="mobiIe" />
</dd>
</dI>
<button>Submit</button>
</form>

class MainContent extends React.Component

render(){
return(
<div className="container-fIuid">
<h3>Event HandIing</h3>
<EventsDemo />
</div>
ReactDOM.render(
<MainContent />,
document.getEIementById(moot')

Touch Events
Specifies interactions with devices that support
“Touch”. User can touch, swipe using pointing devices
or even mouse.
- onTouchStart : When user starts swipe
- onTouchMove : While swiping on screen
- onTouchEnd : When user ends swipe.

Every Touch event comprises of3 major properties


related to “Touch”

- touches
- targetTouches
- changedTouches
Ex:Touch Event
App.js
class TouchEvent extends React.Component

constructor(props){
super(props);
this.state ={
shoeName:"

this.TouchStart = this.TouchStart.bind(this);

TouchStart(e){
if(e.touches[0].clientX >= 24 &&
e.touches[0].cIientX<=203){
this.setState({
shoeName: 'Nike Casuals'
if(e.touches[0].clientX >= 230 &&
e.touches[0].cIientX<=401){
this.setState({
shoeName: 'Lee Cooper Boot’

render(){
return(

<div onTouchStart={this.TouchStart)>
<img src=”shoe.jpg" width="2O0" height="200" />
<img src=”shoe1.jpg" width="200" height="200” />
</div>
<h2>You Touched {this.state.shoeName} </h2>
class MainContent extends React.Component

render(){
return(
<div className="container-fIuid">
<h3>Event HandIing</h3>
<TouchEvent/>
</div>

ReactDOM.render(
<MainContent />,
document.getEIementById('root')

Ex:
App.js

class TouchEvent extends React.Component

constructor(props){
super(props);
this.state ={
styleobj {
position: 'fixed',
top: ",
left:"

this.TouchStart = this.TouchStart.bind(this);

TouchStart(e){
this.setState({
styleobj:{
position: 'fixed',
left: e.touches[0].clientX+ 'px',
top: e.touches[0].clientY+ 'px'

render(){
return(

<div onTouchStart={this.TouchStart)>
<img style={this.state.styleobj} src="baII.png”
height="50" width="50"/>
</div>

class MainContent extends React.Component

render(){
return(
<div className="container-fIuid">
<TouchEvent/>
</div>

ReactDOM.render(
<MainContent />,
document.getEIementById('root')

onTouchStart : It fires up when user starts the


touch.
onTouchMove . It fires up while dragging on
touch.
onTouchEnd - It fires up when touch stopped.

How to handle swipe on application?


- Swipe uses the3 touch events
o TouchStart
o TouchMove
o TouchEnd
- You can access the touch property called
“onswiped” and “onswipping”
Ex:
App.js
class TouchEvent extends React.Component

constructor(props){
super(props);
this.state ={
styleobj {
position: 'fixed',
top: ",
left:"

ads {
position 'fixed',
top: ",
left:"
this.TouchStart = this.TouchStart.bind(this);
this.MoveAd = this.MoveAd.bind(this);

TouchStart(e){
this.setState({
styleobj:{
position: 'fixed',
left: e.touches[0].clientX+ 'px',
top: e.touches[0].clientY+ 'px'

MoveAd(e){
this.setState({
ads:{
position: 'fixed',
left: e.touches[0].clientX+ 'px',
top: e.touches[0].clientX+ 'px'
render(){
return(

<div onTouchMove={this.MoveAd)
style=(this.state.ads) className="card”>
<div className="card-header">
<h3>Ads - Nike</h3>
</div>
<div className= card-body”>
<img src=shoe.jpg width="50 height="50I
</div>
</div>
<div onTouchMove={this.TouchStart}>
<img style={this.state.styleobj} src="baII.png”
height="50" width="50"/>
</div>
</>
class MainContent extends React.Component

render(){
return(
<div className="container-fIuid">
<TouchEvent/>
</div>

ReactDOM.render(
<MainContent />,
document.getEIementById('root')

Conditional Rendering in React


- A component can render specified content in UI.
- It is defined by using “render()” method.
- In various situationsa component must able to
render different types of contents.
- You can design component with conditional
rendering, so that it can render content according
to state and situation.
- It requires the traditional JavaScript operator like
“if, switch, ternary etc.”

function LoginSuccess(props){
return <h2>Login Success..</h2>

function LoginFaiIure(props){
return <h2>Login Failed..</h2>

class MainContent extends React.Component

constructor(props){
super(props);
this.state ={
statusmsg: false,
content:"

this.LoginCIick = this.LoginCIick.bind(this);

LoginCIick(e){

if(e.target[0].vaIue==’john' &&
e.target[1].vaIue==’admin’)

this.setState({
content: <LoginSuccess />

} else{
this.setState({
content: <LoginFaiIure />
render(){
return(

<h3>User Login</h3>
<form onsubmit={this.LoginClick)>
<dI>
<dt>User Name</dt>
<dd><input type=”text"/></dd>
<dt>Password</dt>
<dd><input type=”password"/></dd>
</dI>
<button>Login</button>
</form>
<div>
{this.state.content)
</div>
<f>
ReactDOM.render(
<MainContent />,
document.getEIementById('root’)

Ex:Changing the View using condition - Views are


configured as separate components.
function EditView(){
return(
<div>
Price:
<input type="text" />
<button>Save</button>
</div>

function DisplayView()(
return(
<div>
Price <IabeI></IabeI>
<button>Edit</button>
</div>

class ProductComponent extends React.Component

constructor(props){
super(props);
this.state ={
product:{
Name: 'JBL Speaker’,
Price: 5300.33,
Photo: ’speaker.jpg'

viewName: 'display’

render(){
if(this.state.viewName=='display'){
return(
<DispIayView />

) else{
return(
<EditView />

class MainContent extends React.Component{


render(){
return(
<div className="container-fIuid">
<ProductComponent />
</div>
ReactDOM.render(
<MainContent/>,
document.getEIementById('root')

Ex: Changing view without defining separate


components.

class ProductComponent extends React.Component

constructor(props){
super(props);
this.state ={
product:{
Name: 'JBL Speaker’,
Price: 5300.33,
Photo: ’speaker.jpg’
viewName: 'edit’

render(){
if(this.state.viewName=='display'){
return(
<div>
Price <IabeI></IabeI>
<button>Edit</button>
</div>

) else{
return(
<div>
Price:
<input type="text” />
<button>Save</button>
</div>
class MainContent extends React.Component{
render(){
return(
<div className="container-fIuid">
<ProductComponent />
</div>

ReactDOM.render(
<MainContent/>,
document.getEIementById('root')

Ex: Editing Record


class ProductComponent extends React.Component

constructor(props){
super(props);
this.state ={
product:{
Name: 'JBL Speaker’,
Price: 5300.33,

newProduct:{
Name: ”,
Price:"

viewName: 'display’

this.EditCIick = this.EditCIick.bind(this);
this.SaveCIick = this.SaveCIick.bind(this);
this.ChangePrice = this.ChangePrice.bind(this);
this.ChangeName = this.ChangeName.bind(this);
EditClick(){
this.setState({
viewName: 'edit'

SaveClick(){
this.setState({
viewName: 'display',
product:{
Name: this.state.newProduct.Name,
Price: this.state.newProduct.Price

ChangePrice(e){
this.setState({
newProduct:{
Name: this.state.newProduct.Name,
Price: e.target.value
ChangeName(e){
this.setState({
newProduct:{
Name: e.target.value,
Price: this.state.newProduct.Price

render(){
if(this.state.viewName=='display'){
return(
<div>
<tabIe width=tI300 border="1">
<thead>
<tr>
<th>Name</th>
<th>Price</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr>
<td> {this.state.product.Name}</td>
<td> {this.state.product.Price} </td>
<td»«button onClick={this.EditClick)
>Edit</button></td>
</tr>
</tbody>
</tabIe>
</div>

) else{
return(
<div>
<tabIe width="300” border="0">
<thead>
<tr>
<th>Name</th>
<th>Price</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr>
<td> <input types text"
onChange={this.ChangeName}
value={this.state.newProduct.Name}/></td>
<td> <input type="text"
onChange={this.ChangePrice}
value={this.state.newProduct.Price}/> </td>
<td»«button onClick={this.SaveClick)
>Save</button></td>
</tr>
</tbody>
</tabIe>
</div>
class MainContent extends React.Component{
render(){
return(
<div className="container-fIuid">
<ProductComponent />
</div>

ReactDOM.render(
<MainContent/>,
document.getEIementById(moot')

Ex: Editable Table Row

class ProductComponent extends React.Component


constructor(props){
super(props);
this.state ={
product:{
Name: 'JBL Speaker',
Price: 5300.33,

newProduct:{
Name: ”,
Price:"

viewName: 'display'

this.EditCIick = this.EditCIick.bind(this);
this.SaveCIick = this.SaveCIick.bind(this);
this.ChangePrice = this.ChangePrice.bind(this);
this.ChangeName = this.ChangeName.bind(this);

EditClick(){
this.setState({
viewName: 'edit’,
newProduct:{
Name: this.state.product.Name,
Price: this.state.product.Price

SaveClick(){
this.setState({
viewName: 'display’,
product:{
Name: this.state.newProduct.Name,
Price: this.state.newProduct.Price

ChangePrice(e){
this.setState({
newProduct:{
Name: this.state.newProduct.Name,
Price: e.target.value

ChangeName(e){
this.setState({
newProduct:{
Name: e.target.value,
Price: this.state.newProduct.Price

render(){
if(this.state.viewName=='display'){
return(
<div>
<tabIe width="300" border="1">
<thead>
<tr>
<th>Name</th>
<th>Price</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr>
<td> {this.state.product.Name}</td>
<td> {this.state.product.Price} </td>
<td»«button onClick={this.EditClick)
>Edit</button></td>
</tr>
</tbody>
</tabIe>
</div>

) else{
return(
<div>
<tabIe width="300” border="0">
<thead>
<tr>
<th>Name</th>
<th>Price</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr>
<td> <input type="text"
onChange={this.ChangeName}
value={this.state.newProduct.Name}/></td>
<td> <input type="text"
onChange={this.ChangePrice}
value={this.state.newProduct.Price}/> </td>
<td»«button onClick={this.SaveClick)
>Save</button></td>
</tr>
</tbody>
</tabIe>
</div>

class MainContent extends React.Component{


render(){
return(
<div className="container-fIuid">
<ProductComponent />
</div>

ReactDOM.render(
<MainContent/>,
document.getEIementById('root')
Handling Multiple Conditions
- You can use “if..else if.. else”
- You can use “switch..case..default”
- You can use “ternary” ?:

Ex: Rendering with “if..else if.. else”


class ProductComponent extends React.Component

constructor(props){
super(props);
this.state ={
viewName:"

render(){
if(this.state.viewName=='Basic'){
return(
<div>
<h3>Basic DetaiIs</h3>
</div>

} else if (this.state.viewName==’Preview’){
return(
<div>
<h3>Product Preview</h3>
</div>

} else{
return(
<div>
<h3>Summary</h3>
</div>

class MainContent extends React.Component{


render(){
return(
<div className="container-fIuid">
<ProductComponent />
</div>

ReactDOM.render(
<MainContent/>,
document.getEIementById('root')

FAQ: How to render nothing if value is not among


specified conditions?
A.You have to configure the render method to
return “null” if condition is not matching.

EX: Multiple conditions using ternary operator

this.state.viewName=='Details'?
<h3>DetaiIs</h3>:
this.state.viewName=='Preview'?
<h3>Preview</h3>:
<h3>Summary</h3>

Ex:
function Basiclnfo(){
return(
<div>
<h2>Basic Info</h2>
<div className="card”>
<div className="card-header">
<h2>JBL Speaker</h2>
<p>Price: &#8377; 6700.66/-</p>
</div>
</div>
</div>
function Preview(){
return(
<div>
<h2>Preview</h2>
<div className=”card">
<div className="card-body">
<img src="speaker.jpg" width="200" height="200”
/>
</div>
</div>
</div>

function Description(){
return(
<div>
<h2>Description</h2>
<div className=”card">
<div className="card-header">
<h3>Features</h3>

V
<Ii>Feature-1</Ii>
<Ii>Feature-2</Ii>
<Ii>Feature-3</Ii>
</uI>
</div>
</div>
</div>

class ProductComponent extends React.Component

constructor(props){
super(props);
this.state ={
viewName: 'Description’,
container:"
this.ViewChanged = this.ViewChanged.bind(this);

ViewChanged(e){
switch(e.target.name)

case "Basiclnfo
this.setState({
container: <BasicInfo />

break;
Case "Previewing
this.setState({
container: <Preview />
›):
break;
case "Description":
this.setState({
container: <Description />
break;

render(){
return(
<div>
<h2>Product DetaiIs</h2>
<div className="btn-tooIbar”>
<div className="btn-group">
<button onClick={this.ViewChanged}
names Basiclnfo classNamem btnbtn-primary Basic
Info</button>
<button onClick={this.ViewChanged}
name="Preview" cIassName=”btn btn-
info">Preview</button>
<button onClick={this.ViewChanged}
name="Description" cIassName="btn btn-
danger”>Description</button>
</div>
</div>
<div>
{this.state.container}
</div>
</div>

class MainContent extends React.Component{


render(){
return(
<div className="container-fIuid">
<ProductComponent />
</div>

ReactDOM.render(
<MainContent/>,
document.getEIementById (moot')

Component Lifecycle
- Every component hasvarious phases.
- The component in “React” is responsible for
managing various interactions in an order
implicitly.
- Component comprises various lifecycle methods
that executed to handle various interactions.
- You have to override the lifecycle methods to
improve the performance of application.
- You can prevent memory leaks; cross page posting
and can improve the load time and performance.
- Every component comprises of3 phases
o Mounting
o Updating
o Unmounting

Mounting: Whena component is initialized


- getDefaultProps
- getlnitialstate
- componentWillMount
- render
- componentDidMount
Updating: Whena component hasstate changed
[Change Detection]
- shouldComponentUpdate - comprises of value
before update
- componentWillUpdate
- render
- componentDidUpdate - comprises of value after
update
Unmounting: Whena component is unmounting.
[Cleaning up/ destroying]
- componentWillUnmount

Ex: Component Mount and Unmount


App.js
class ProductComponent extends React.Component

constructor(props){
super(props);
this.state ={
date: new Date()

timer(){
this.setState(
date: new Date(),
psig ..

this.componentWiIIUnmount =
this.componentWiIIUnmount.bind(this);

displaytime;
componentDidMount(){
this.dispIaytime = setlnterval(()=> this.timer(),
1000);
this.setState({
msg: 'Component Mounted’

alert("Component Mounted”);

componentWillUnmount(){
clearlnterval(this.displaytime);
this.setState({
msg: 'Component Unmounted| Cleaned Up’
Refresh(){
location.reload();

render(){
return(
<div>
<button onClick={this.componentWillUnmount)
>Unmount</button>
<button onClick={this.Refresh}>Refresh</button>
<p>{this.state.date.toLocaIeTimeString()}</p>
<p>{this.state.msg}</p>
</div>

class MainContent extends React.Component{


render(){
return(
<div className="container-fIuid">
<ProductComponent />
</div>

ReactDOM.render(
<MainContent/>,
document.getEIementById('root')

Ex:
App.js
class SuccessComponent extends React.Component

componentWillMount(){
alert(”Success component requested..");

componentDidMount(){
alert(”Success Component Mounted..");

componentWillUnmount(){
alert(”Success Disposed..");

render(){
return(
<h2>Login Success..</h2>

class ErrorComponent extends React.Component

componentWillMount(){
alert(”Error Component Requested");

componentDidMount(){
alert(”Error Component Mounted..");

componentWillUnmount()(
alert(”Error Disposed..");

render(){
return(
<h2>InvaIid Password</h2>

class ProductComponent extends React.Component

constructor(props){
super(props);
this.state ={
msg:”

this.SuccessCIick = this.SuccessCIick.bind(this);
this.ErrorCIick = this.ErrorCIick.bind(this);

5uccessClick(){
this.setState({
msg: <SuccessComponent />

ErrorClick(){
this.setState({
msg: <ErrorComponent />

render(){
return(
<div>
<button onClick={this.SuccessClick)
>Success</button>
<button onClick={this.ErrorCIick)>Error</button>
<div>
<p>
{this.state.msg}
</p>
</div>
</div>

class MainContent extends React.Component{


render(){
return(
<div className="container-fIuid">
<ProductComponent />
</div>

ReactDOM.render(
<MainContent/>,
document.getEIementById('root')

React Application Interacting with API


Distributed Computing Architecture
- Distributed computing allows2 different
applications running on2 different machines to
share information. OR 2 different applications
running of2 different process in the same machine
can share information.
- There arevarious distributed computing
technologies
o CORBA
o DCOM
o RMI
o EJB
o Web Service [All technologies]
o Remoting etc.
- Web Service Specifications
o SOAP
• Request and Response will in XML
o REST
• Request willa simple query and Response
will in XML or Optionally JSON.
o JSON
• Request and Response will be JSON.
- React requiresa “Tool Chain” to configuring
distribute computing architecture and build
distributed computing apps.
- Client-Side Application is created by using
“Create-React-App” [SPA in React]
o A Package Manager [NPM]
o Bundler [Webpack or Parcel]
o A Compiler [Babel]
- The “Tool Chain” used forReact Distributed
Application
o Next.js — Framework forstatic and server-
rendered applications [Node.js, JSP, .NET,
PHP].
o Gatsby — Forcreating static website with
React. [Improve the load time]
o Nx — tool kit for “Full Stack development”
using React. [React, Next.js, Express,
MongoDB]
o Razzle - Server-Side Rendering Framework
o Ionic, Native Script, Cordova — Framework to
build cross platform mobile app with React.

- Creatinga Client Side React Application


o Install Node.js 8+ version
o Run the command
> npm install -g create-react-app
o Run the command
> npxcreate-react-app amazon
o To Start your application
> npm start
Createa new Database in MongoDB
Download and Install MongoDB database server
on your PC.
https://www.mongodb.com/try/download/communi

- Start MongoDB Server


Open 4 Services.msc 4 MongoDB Server [Right
Click and Start]
- Connect to MongoDB server from client
C:\Program
Files\MongoDB\Server\4.4\bin>mongo.exe

MongoDB Terminology:
RDBMS MongoDB
Database Database
Table Collection
Records/ Rows Documents
Field Field
Joins Embedded Documents

MongoDB Commands: [Case sensitive]


- To View thelist of existing databases
> show dbs
- To createa new database
> use databaseName
> use shoppingdb
- To Createa new Table [Collection] in Database
> db.createCoIIection(“tabIeName”)
> db.createCoIIection(“tbIproducts”)
- To View thetables in database
> show collections
- To Add records into table [Collection]

db.coIIectionName.insertOne({FieldName:value,
FieldName: value})
> db.coIIectionsName.insertMany([{ },{ },{ )])
Ex:
> db.tbIproducts.insertOne({ProductId:1, Name: "JBL
Speaker", Price: 4500.55, InStock:true))
> db.tbIproducts.insertMany([{ProductId:2,
Name:’Earpods', Price: 6000.55,
lnstock:true},{ProductId:3, Name: 'Nike Casuals’, Price:
7000.44, InStock:true}])

- To View Documents present in Collection


> db.coIIectionName.find({query})
> db.tbIproducts.find().pretty()

Create Web API/ Service using Server-Side


Technology
[Node.js — Server-Side Scripting, Express — Middleware]
- Go to Your “ReactFullStack” project
- Createa new Folder “Server”
- Install following packages
> npm install mongodb [database connection]
> npm install express [middleware]
- Createa new JavaScript file [Node.js] by name
“api.js”

Api.js
var mongoClient = require("mongodb").MongoClient;
var express = require("express");
var url = "mongodb://127.0.0.1:27017";
var app = express();
app.get("/getproducts", function(req, res){
mongoClient.connect(url, function(err, clientobj){
if(!err){
var database = cIientObj.db(”shoppingdb”);
database.collection("tbIproducts").find().toArray(functi
on (err, documents){
if(!err){
res.send(documents);

app.listen(8080);
console.log( Server Started: http://127.0.0.1:8080II)t

Product.js
import React from 'react",
import$ from 'jquery",
export default class ProductComponent extends
React.Component{
constructor(props){
super(props);
this.state ={
Productld: ",
Name: ”,
Price: 0,
InStock: false

componentDidMount(){
this.fetch();

fetch(){
var context = this;
$.ajax({
url: 'http://127.0.0.1:8080/getproducts',
method: 'GET',
success: function(response){
context.setState({
Productld: response[0].Productld,
Name: response[0].Name,
Price: response[0].Price,
InStock: response[0].InStock
render(){
return(
<div>
<h2>Get Data from API</h2>
<dI>
<dt>Product Id</dt>
<dd>{this.state.ProductId)</dd>
<dt>Name</dt>
<dd>{this.state.Name)</dd>
<dt>Price</dt>
<dd>{this.state.Price)</dd>
</dI>
</div>
Consume REST API using jQuery Ajax in React
- Createa new Database Table in MongoDB
Database: amazondb
Collection: tblproducts
- Createa new folder by name “Server”.
- Install the following packages into server folder
> npm install mongodb --save
> npm install express --save
> npm install cors --save
- Createa new JavaScript file “api.js”
Api.js
var mongoClient = require("mongodb").MongoClient;
)
Var express = require("express
var cors = require("cors");

var url = mongodb://127.0.0.1:27017";


var app = express();
app.use(cors());

app.get("/getproducts", function(req, res){


mongoClient.connect(url, function(err, clientobj){
if(!err){
var dbo = cIientObj.db(”amazondb");
dbo.collection("tblproducts").find().toArray(function(er
r, documents){
if(!err){
res.send(documents);

app.listen(8080);
console.log( Server Started: http://127.0.0.1:8080”);
- Start API
> node api.js
- Go to “React Application”
- Go to “src” and add the file
“ProductComponent.js”
ProductComponent.js

import React from 'react",


import$ from 'jquery",
export default class ProductComponent extends
React.Component

constructor(props){
super(props);
this.state ={
products: []

componentDidMount(){
this.fetch();

fetch(){
var context = this;
$.ajax({
url: 'http://127.0.0.1:8080/getproducts',
method: 'GET',
success: function(response){
context.setState({
products: response
render(){
return(
<div>
<h2>Products List </h2>
<tabIe width=”400” border="1”>
<thead>
<tr>
<th>Product Id </th>
<th>Name </th>
<th>Price </th>
</tr>
</thead>
<tbody>

this.state.products.map(product =>
<tr key={product.Productldj»
<td>(product.ProductId)</td>
<td>(product.Name)</td>
<td>{product.Price)</td>
</tr>

</tbody>
</tabIe>
</div>

- Go to Index.js
import React from ’react",
import ReactDOM from 'react-dom",
import './index.css
import App from ’./App
import reportWebVitals from ’./reportWebVitals",
import ProductComponent from
'./ProductComponent",

ReactD0M.render(
<React.StrictMode>
<ProductComponent />
</React.StrictMode>,
document.getEIementById(’root')
)*

// If you want tostart measuring performance in


your app, passa function
// to log results (for example:
reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more:
https://bit.Iy/CRA-vitaIs
reportWebVitals();

Consuming REST API using Fetch


- jQuery uses “Ajax” explicitly to connect with API.
- Fetch uses window.fetch, which implicitly uses
XmlHttpRequest.
- Fetch will return the data, which need to be
parsed into JSON.
- Fetch provides various details in response data.
- You have to convert data into JSON.
Ex:
ProductsDataComponent.js
import React from 'react",

export default class ProductsDataComponent extends


React.Component

constructor(props){
super(props);
this.state ={
products: []
componentDidMount(){
fetch("http://127.0.0.1:8080/getproducts")
.then(response => response.json())
.then(response =>{
this.setState({
products: response

render(){
return(
<div>
<h2>Products List</h2>
Il
<tabIe width= 400" border=1 I
<thead>
<tr>
<th>Product Id</th>
<th>Name</th>
<th>Price</th>
</tr>
</thead>
<tbody>

this.state.products.map(product =>
<tr key={product.ProductId)>
<td>{product.ProductId)</td>
<td>{product.Name)</td>
<td>{product.Price)</td>
</tr>

</tbody>
</tabIe>
</div>

Consuming APIs with Axios


- Axios can handle data by default in JSON format.
- Fetch requires explicit JSON parsing.
- Axios converts the data into JSON and provides to
application.
- It can make used of “async and await” for handling
Asynchronous requests.
- It is provided with built-in Request Forgery Token.
That prevents Cross Page Posting.
[XSRF], [XSS]

Features of Axios:
- Default data format is JSON.
- Provides streamlined Error Handling
- Protection against XSRF.
- Response timeout.
- Ability to cancel the request.
- Uses await and async.
- Supports CORS
- Supports Legacy Browsers [Old Version]

Requests with Axios:


axios({
method: ‘GET’,
url: ‘api_urI’
›):
axios({
method: ‘POST’,
url: ‘api_urI’,
data:( )

Shorthand Requests
axios.get(url)
axios.post(url, data[])
axios.put()
axios.delete()

Axios can handle multiple Requests:


Syntax:
axios.all([
axios.get(URL), [0]
axios.get(URL), [1]

then(response=>{
console.log(‘First URL’, response[0].data),
console.log(‘SecondURL’, response[1].data)

You have to use the state Hooks ofReact to handle


interaction with APIs
- usestate()
- useEffect()
- useContext()
- useReducer()

usestate():
- It allows React developers to update, handle and
manipulate state inside functional components
without converting into class component.
Syntax:
function App(){
const [name, setName] = useState(‘John’);
OnButtonClick = () => setName(‘David’);

return <div> {name) </div>


Axios in React Application
- Install axios for your project
> npm install axios
- Add a new file into “src”
ProductDetaiIsComponent.js

import React from ’react",


import axios from ’axios",

export default class ProductDetailsComponent


extends React.Component
constructor(props){
super(props);
this.state ={
products: []

componentDidMount(){
axios.get("http://127.0.0.1:8080/getproducts”)
.then(res =>{
this.setState({
products: res.data

render(){
return(
<div>
<h2>Products List</h2>
<tabIe width="400” border=”1">
<thead>
<tr>
<th>Product Id</th>
<th>Name</th>
<th>Price</th>
</tr>
</thead>
<tbody>

this.state.products.map(product =>
<tr key=(product.ProductId)>
<td>{product.ProductId)</td>
<td>{product.Name)</td>
<td>(product.Price)</td>
</tr>

</tbody>
</tabIe>
</div>

Note: You can also use “whatwg-fetch” forfetching


remote data.

Posting Data to Remote API


- Server-side API must be configured with POST
method.
- Install “body-parser” in your server-side project
> npm install body-parser
- Create “Post” URL in your Server-Side API
Api.js
var mongoClient = require(“mongodb”).MongoClient;
var express = require(“express”);
var cors = require(“cors”);
var bodyParser = require(“body-parser”);

var url = “mongodb://127.0.0.1:27017”;


var app = express();
app.use(cors());
app.use(bodyParser.urlencoded({
extended: true
1)):
app.use(bodyParser.json());

app.get(“/getproducts”, function(req, res){


mongoClient.connect(url, function(err, clientobj){
if(!err){
var dbo = cIientObj.db(“amazondb”);
dbo.collection(“tblproducts”).find().toArray(function(er
r, documents){
if(!err){
res.send(documents);

app.post(“/addproduct”, function(req, res){


mongoClient.connect(url, function(err, clientobj){
if(!err){
var dbo = cIientObj.db(“amazondb”);
var data ={
Productld: req.body.Productld,
Name: req.body.Name,
Price: req.body.Price
dbo.collection(“tblproducts”).insertOne(data,
function(err, result){
if(!err){
console.log(“Record Inserted”);
) else{
console.log(err.message);

app.listen(8080);
console.log(“Server Started: http://127.0.0.1:8080”);

Createa React Component Posting Data into API


ProductDetailsComponent.js
import React from ’react“,
import axios from ’axios“,

export default class ProductDetailsComponent extends


React.Component
constructor(props){
super(props);
this.state ={
products: [],
g

data:(
Productld: 0,
Name: ",
Price:0

this.IdChanged = this.IdChanged.bind(this);
this.NameChanged =
this.NameChanged.bind(this);
this.PriceChanged = this.PriceChanged.bind(this);

componentDidMount(){
axios.get("http://127.0.0.1:8080/getproducts")
.then(res =>{
this.setState({
products: res.data,
msg: res.status

IdChanged = event =>{


this.setState({
data {
Productld: event.target.value,
Name: this.state.data.Name,
Price: this.state.data.Price,

NameChanged = event =>{


this.setState({
data {
Productld: this.state.data.Productld,
Name: event.target.value,
Price: this.state.data.Price,

PriceChanged = event =>{


this.setState({
data {
Productld: this.state.data.Productld,
Name: this.state.data.Name,
Price: event.target.value,

SubmitClick = event =>{

const data ={
Productld: this.state.data.Productld,
Name: this.state.data.Name,
Price: this.state.data.Price
axios.post(”http://127.0.0.1:8080/addproduct”,
data)
.then(res =>{
console.log('Record Inserted’);
console.log(res.data);

alert("Record Inserted”);

render(){
return(
<div cIassName="container
<h2>Add Product</h2>
<form onsubmit={this.SubmitCIick)>
<div>
<dI>
<dt>Product Id</dt>
<dd><input type="text”
onChange={this.IdChanged)/></dd>
<dt>Name</dt>
<dd><input type="text”
onChange={this.NameChanged}/></dd>
<dt>Price</dt>
<dd><input type="text”
onChange={this.PriceChanged}/></dd>
</dI>
<button>Add Product</button>
</div>
</form>
<h2>Products List {this.state.msg} </h2>
<tabIe cIassName="tabIe table-hover">
<thead>
<tr>
<th>Product Id</th>
<th>Name</th>
<th>Price</th>
</tr>
</thead>
<tbody>

this.state.products.map(product =>
<tr key={product.ProductId)>
<td>{product.ProductId}</td>
<td>{product.Name}</td>
<td>{product.Price}</td>
</tr>

</tbody>
</tabIe>
</div>

Forms in React
- Form provides an UI that allows the users to
interact with application.
- React JS supports one way binding, hence handling
interaction with form requires “State”.
- Class component can maintain state for form.
- Functional component is state less hence it
requires “usestate()” hook.
- You can configurea state hook forevery element
and access its value.
Ex:
import React from 'react",

export default function FormDemo(){


const [productname, setName] = React.useState("”);
const [productprice, setPrice] = React.useState("");
const [shippedto, setShippedTo] =
React.useState("");
const [instock, setstock] = React.useState("Yes");

const submitClick = (event) =>{


document.write(”
Name=g{productname) <br>
Price=g(productprice) <br>
Shipped To=g{shippedto) <br>
InStock =g{instock)
return(
<form onsubmit={submitCIick}>
<h2>Register Product</h2>
<div className="form-group”>
<IabeI>Name</IabeI>
<div>
<input onChange={e=>
setName(e.target.value)} name="productname"
value={productname} cIassName="form-control"
type="text” />
</div>
</div>
<div className=”form-group”>
<IabeI>Price</IabeI>
<div>
<input
onChange={e=>setPrice(e.target.value))
name="productprice" value={productprice}
cIassName="form-control” type="text"/>
</div>
</div>
<div className=”form-group”>
<IabeI>Shipped To</IabeI>
<seIect
onChange={e=>setShippedTo(e.target.value)}
name=)shippedto" value={shippedto}
cIassName="form-control">
<option>DeIhi</option>
<option>Hyd</option>
<option>Mumbai</option>
</seIect>
</div>
<div className="form-group”>
<IabeI>In Stock</IabeI>
<div>
<input value={instock}
onChange={e=>setStock(e.target.value)}
names instock type="checkbox > Yes
</div>
</div>
<div class="form-group”>
<button cIassName="btn btn-primary btn-
block >Register</button>
</div>
</form>
)*

Accessing Data from Multiple Form Elements


- Createa state for handling multiple values
Syntax:
this.state ={
product {
Id: ‘,
Name:

- Bind the state with elements


<input type=”text” value={this.state.product.Id)
name=”Id />
- Configure event binding for element
<input type=”text”
onChange={this.handleChange}/>
- Define the event method toaccess the name and
value of element
handIeChange(event)

name = event.target.name;
value = event.target.value;
this.setState({
product {
...this.state.product,
[name] value

Ex:
FormDemo.js
import React from react",
export default class FormClassDemo extends
React.Component

constructor(props){
super(props);
this.state ={
product {
Productld: Ill
Name: ",
Price:"

this.updateFormData =
this.updateFormData.bind(this);
updateFormData(event){
const name = event.target.name;
const value = event.target.value;
this.setState({
product {
...this.state.product,
[name] value

render(){
return(
<div>
<dI>
<dt>Product Id</dt>
<dd>
<input type=”text” name=”ProductIdII
value={this.state.product.Productld)
onChange={this.updateFormData}/>
</dd>
<dt>Name</dt>
<dd>
<input type=”text” name=”Name"
value={this.state.product.Name)
onChange={this.updateFormData)/>
</dd>
<dt>Price</dt>
<dd>
<input type=”text" name=”Price"
value={this.state.product.Price}
onChange={this.updateFormData}/>
</dd>
</dI>
<h3>Product DetaiIs</h3>
<dI>
<dt>Product Id</dt>
<dd>{this.state.product.ProductId}</dd>
<dt>Name</dt>
<dd>{this.state.product.Name}</dd>
<dt>Price</dt>
<dd>{this.state.product.Price)</dd>
</dI>
</div>

External Library for Designing the Form


- Formik isa library used forbuilding complex forms
and handling validation.
- Formik isa group of React components and hooks
forbuilding and validating forms.
- The library of “formik provides hooks and
component, which are accessed using “formik”
prefix.
Syntax:
<form onsubmit= {formik.handIeSubmit}>
<input type=”text” value={formik.values.Nam}/>
- In order to use Formik in your React component.
You have to inject “useFormik”.

Ex:
import React from ’react",
import {useFormik) from 'formik",
const FormLibraryDemo =() =>{
const formik = useFormik({
initialValues:{
Productld: ",
Name: ",
Price:

onsubmit: values =>{


console.log(JSON.stringify(values));

return(
<div>
<form onsubmit={formik.handlesubmit}>
<dI>
<dt>Product Id</dt>
<dd>
<input type="text" name= roductldll
value={formik.values.Productld}
onChange={formik.handleChange)/>
</dd>
<dt>Name</dt>
<dd>
<input type="text" name="Name"
value={formik.values.Name}
onChange={formik.handleChange)/>
</dd>
<dt>Price</dt>
<dd>
<input type="text" name="Price"
value={formik.values.Price)
onChange={formik.handleChange)/>
</dd>
</dI>
<button>Register</button>
</form>
</div>

export default FormLibraryDemo;

Validations in React Form


- Validation is the process of verifying user input.
- Validation is required to ensure that
contractionary and unauthorized data is not get
stored into database.
- Validation can be handled manually or by using
pre-defined library functions and properties.
- Formik supports synchronous and asynchronous
validations.
- Formik handles validation at2 levels
o Formstate validation/ Form-level validation
o lnputstate validation/ Field-level validation
- “Yup” is used forSchema based validation.
- Formik uses various methods/events forvalidating
the values
o After Change events/methods
• handleChange
• setFieldValue
• setValues
o After Blur events/methods
• handleBlur
• setTouched
• setFieldTouched
o After Submit events/methods
• handlesubmit
• submitForm
Ex:
import React from 'react",
import ReactDOM from 'react-dom",
import {useFormik) from 'formik",

const validateProduct = productData =>{


const errors = {)
if(!productData.Name){
errors.Name = ’Product Name Required",
) else if(productData.Name.Iength<4){
errors.Name = ’Name tooshort..Min4 required",

if(!productData.Price){
errors.Price = ’Product Price Required",

if(!productData.Code){
errors.Code = 'Product Code Required",
) else if (!/[A-Z]{3)[0-9]{2)/.test(productData.Code)){
errors.Code = 'Invalid Code..",

return errors;

const RegisterProductComponent = () => {


const formik = useFormik({
initialValues:{
Name: ",
Price: ",
Code:"

validate: validateProduct,
onsubmit: values =>{
alert(JSON.stringify(values));

return(
<div>
<h2>Register Product</h2>
<form onsubmit={formik.handIeSubmit)>
<div className=”form-group”>
<IabeI>Name</IabeI>
<div>
<input name="Name"
onBlur={formik.handleBlur}
onChange={formik.handleChange}
value={formik.values.Name) type="text" />
<div className=”text-danger">
{(formik.touched.Name &&
formik.errors.Name)?formik.errors.Name:null}
</div>
</div>
</div>
<div className=”form-group”>
<IabeI>Price</IabeI>
<div>
<input type=”text"
on Blur={formik.handleBlur}
onChange={formik.handleChange} name= rice
value={formik.values.Price) />
<div className=”text-danger">
{(formik.touched.Price &&
formik.errors.Price)?formik.errors.Price:null}
</div>
</div>
</div>
<div class=”form-group">
<IabeI>Code</IabeI>
<div>
<input onBlur={formik.handleBlur}
onChange={formik.handleChange} name="Code”
value={formik.values.Code} type=”text” />
<div classNamem text-danger”>
{(formik.touched.Code &&
formik.errors.Code)?formik.errors.Code:null}
</div>
</div>
</div>
<div className=”form-group”>
<button>Register</button>
</div>
</form>
</div>

ReactDOM.render(
<RegisterProductComponent />,
document.getEIementById(”root")

export default RegisterProductComponent;

Yup Library
- It provides object schema validation.
- It providesa validationschema object.
- Schema object comprises of key and value
reference.
- It uses an error object that can bind with any
HTML element and configure the validations for
element.
- It comprises of Key and Value reference, where
keyrefers to validation error and value refers to
validation message.
Syntax:
validationschema: yup.object({
Name:
yup.DataType().required().max().email()

- Yup library uses “formik.getFieIdProps()” that can


give access to values of elements.
Syntax:
<input type=”text” name=”Name”
(...formik.getFieIdProps(“Name”)) />

Ex:
YupVaIidationDemo.js
import React from react“,
import {useFormik} from 'formik",
import* as yup from ’yup",

const YupValidationComponent = () => {


const formik = useFormik((
initialValues:{
Name: ”,
Salary: ",
Email:"
validationschema: yup.object({
Name: yup.string()
.min(4, "Name tooshort..min4 chars")
.max(10, "Name toolong.. max 10 chars )
.required("User Name Required )
Salary: yup.number()
.required("Salary Required"),
Email: yup.string()
.required("Email Required")
.email("Invalid Email")
›),
onsubmit: values =>{
alert(JSON.stringify(values))

return(
<div>
<h2>Register User</h2>
<form onsubmit={formik.handIeSubmit}>
<dI>
<dt>Name</dt>
<dd>
<input type="text" name="Name"
{...formik.getFieIdProps("Name”)) />
</dd>
<dd className=”text-danger">
{(formik.touched.Name &&
formik.errors.Name)? formik.errors.Name: null)
</dd>
<dt>SaIary</dt>
<dd>
<input type="text" name="SaIary”
{...formik.getFieIdProps("Salary”)) />
</dd>
<dd className=”text-danger">
{(formik.touched.Salary &&
formik.errors.Salary)? formik.errors.Salary: null}
</dd>
<dt>EmaiI</dt>
<dd>
<input type="text" name="EmaiI"
{...formik.getFieIdProps("Email"))/>
</dd>
<dd className=”text-danger">
{(formik.touched.Email &&
formik.errors.Email)? formik.errors.Email: null)
</dd>
</dI>
<button>Register</button>
</form>
</div>

export default YupValidationComponent;

Formik Components
- Formik library provides pre-defined component
used fordesigninga form and its validations.
- The built-in components ofFormik library
o <Formik />
o <Form />
o <FieId />
o <ErrorMessage />

Syntax:
<formik initialValues ={
{ Name: ‘, Salary: ‘, Email: }

validationschema ={

onsubmit ={

{ props =>(
<Form>
<FieId name=”Name” type=”text”>
</FieId>
<ErrorMessage name=”Name”>
</ErrorMessage>
</Form>

Syntax:
<Formik initialValues={} validationschema={}
onSubmit={}>

props=> ()

</Formik>

Props function in Formik is responsible for identifying


the state of every field.
dirty : It returns true when anyfield in form is
modified.
touched : It returns true when anyfield is touched
but value not modified.
isValid : It returns true when all form fields are
valid.

Ex:
VaIidationComponent.js
import React from 'react",
import ReactDOM from 'react-dom",
import{ useFormik, Formik, Form, Field, ErrorMessage
} from ’formik",
import” as yup from ’yup",

const ValidationComponent = () => (

return(
<Formik initialValues={

Name: ",
Salary: ",
Email: ",
City:"

) validationschema={
yup.object({
Name: yup.string()
.required(”Name Required")
.min(4, "Name tooshort")
.max(10, "Name toolong )
Salary: yup.number()
.required("Salary Required"),
Email: yup.string()
.required("Email Required")
.email("Invalid Email")

) onsubmit = {vaIues=>{
alert(JSON.stringify(values))

props =>(
<div>
<h3>Register User</h3>
<Form>
<dI>
<dt>Name</dt>
<dd>
<FieId name="Name"
type="text”></FieId>
</dd>
<dd className="text-danger">
<ErrorMessage
name= Name”></ErrorMessage>
</dd>
<dt>SaIary</dt>
<dd>
<FieId name="SaIary"
type= text”></FieId>
</dd>
<dd className="text-danger">
<ErrorMessage
name=)Salary”></ErrorMessage>
</dd>
<dt>EmaiI</dt>
<dd>
<FieId name="EmaiI
type="text”></FieId>
</dd>
<dd className=”text-danger">
<ErrorMessage
name="EmaiI"></ErrorMessage>
</dd>
<dt>Your City</dt>
<dd>
<FieId name="City” as=”seIect">
<option>DeIhi</option>
<option>Hyd</option>
</FieId>
</dd>
</dI>
<button
disabled={props.isVaIid==faIse}>Register</button>
<button
disabled=(props.dirty==faIse)>Save</button>
</Form>
</div>

</Formik>

ReactDOM.render(
<VaIidationComponent/>,
document.getEIementById("root”)

export default ValidationComponent;


Styles using Validation Attributes
- You can dynamically apply styles based on
validation properties
Syntax:
<Form
style={props.isVaIid?{backgroundCoIor:’green’):{backgr
oundColor:’red’})>

Client-Side Routing in React JS


What is Routing?
- Routing is technique used in web applications to
configure User and SEO friendly URL.
- User friendly URL allows to query any content
from URL.
Without Routing:
http://www.amazon.in/electronics.html?category
=eIectronics&modeI=samsung
With Routing:
http://www.amazon.in/electronics/mobile/samsung
- SEO friendly URL allows the web crawlers to
identify the exact location in page.
- In SPA routing allows to access everything from
one page.
- New content will be added into page without
reloading the page.
- Routing can be handled Server-Side and Client-
Side.
- React JS uses routing client-side.

Routing Architecture:

Install Router Module


> npm install —save react-router-dom

Ex:
AppHome.js
import React from ’react“,
import{ BrowserRouter as Router, Route) from 'react-
router-dom",

const Home = () => (


<h2>App Home</h2>

const Contact = () => (


<div>
<address>
NareshlT - Hyd <br />
hr@nareshit.in
</address>
</div>

export default class AppHome extends


React.Component

render(){
return(
<Router>
<Route path=”/" component=(Home) />
<Route path=”/contact" component={Contact) />
</Router>

Switch for Routes


- A <Switch> looks through all its children <Route>
elements and renders the first one whose path is
matching with specified URL.
- Always usea switch to configure set of routes but
only one to render ata time.
Syntax:
<Switch>
<Route path=”” component={ }/>
<Route path=””>
<Home />
</Route>
</Switch>
Redirection of Route
- The element <Redirect> is used in Route to define
redirection to an existing path instead of re-
defining the path and its parameters.
Syntax:
<Route path=”/home”>
<Redirect to=”/” />
</Route>
Route forNo-Match
- If client request can't be processed due to “404”
status code, which is not-found by default it
renders empty page.
- You have configurea generic route with path
defined as “*”, which can render alternative if the
match notfound.
Syntax:
<Route path=”*”>
<NotFound />
</Route>

Note: Always the generic path must be configured at


the end.
- Router library provides “useLocation”, which can
getthe current location details
let location = useLocation();
- You can also use browser location object
window.location.pathname

Configuring Links for Navigation


- Router provides <Link> element, which creates an
anchor that can redirect to specified route path.
Syntax:
<Link to=”/path”> Text </Link>

Ex:
AppHome.js

import React from react",


import {BrowserRouter as Router, Redirect, Route,
Switch, useLocation, Link} from 'react-router-dom",

function Home(){
return(
<div>
<h2>Amazon Home</h2>
<p>Shopping Home Page</p>
</div>

function Electronics(){
return(
<div>
<h2>EIectronics Home</h2>
<img src="Images/speaker.jpg" width=”100"
II I
height= 100

<img src= Images/earpods.jp g width=”100I


height="100" />
</div>

function Footwear(){
return(
<div>
<h2>Footwear Home</h2>
<img src="Images/shoe.jpg" width="100"
II I
height= 100

<img src= Images/shoe1.jpg width="100"


height="100" />
</div>

function Fashion(){
return(
<div>
<h2>Fashion Home</h2>
<img src="Images/shirt.jpg" width=”100"
height="100" />
<img src="Images/jeans.jpg" width="100"
height="100" />
</div>

function NotFound(){

return(
<div>
<h2>Not-Found</h2>
<p>Page you requested <code>
{window.location.href} </code> - Not Found</p>
<p><Link to=”/home”>Back to
Home</Link></p>
</div>

export default class AppHome extends


React.Component

render(){
return(
<Router>
<header>
<h1>Amazon Shopping</h1>
</header>
<div>
<uI style={{dispIay:’flex’, IistStyle:’none’)}>
<Ii><Link to="/home”>Home</Link></Ii>
<Ii><Link
to="/electronics Electronics</Link></Ii>
<Ii><Link
to="/footwear">Footwear</Link></Ii>
<Ii><Link
to="/fashion">Fashion</Link></Ii>
</uI>
</div>
<hr />
<Switch>
<Route exact path=”/">
<Home />
</Route>
<Route path=”/home">
<Redirect tom /I
</Route>
<Route path=”/eIectronics”>
<EIectronics />
</Route>
<Route path=”/footwear”>
<Footwear />
</Route>
<Route path=”/fashion”>
<Fashion />
</Route>
<Route path=”*">
<NotFound />
</Route>
</Switch>
</Router>

Index.html
<!DOCTYPE htmI>
<htmIlangm en
<head>
<meta charset="utf-8" />
<Iink reI="icon" hrefmI%PUBLIC_URLOo/favicon.icons
/^
<meta names viewport contents idth=device-
width, initial-scaIe=1" />
<meta name=”theme-color” content="#000000" />
<meta
name="description"
content=”Web site created using create-react-app"
/^
<Iink reI="appIe-touch-icon
href="OoPUBLIC_URLOo/Iogo192.png” />

manifest.json provides metadata used when your


web app is installed on a
user's mobile device or desktop. See
https://developers.googIe.com/web/fundamentals/we
b-app-manifest/

<Iink reI="manifest"
hrefm''OoPUBLIC_URL Oo/ITlanifest.json

Notice the use of%PUBLIC_URLOo in the tags above.


It will be replaced with the URL of the ”public”
folder during the build.
Only files inside the ”public” folder can be
referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico",
''OoPUBLIC_URL%/favicon.iconswill

work correctly both with client-side routing anda


non-root public URL.
Learn how to configurea non-root public URL by
running "npm runbuild".

<titIe>React App</title>
<Iink
hrefmIhttps://cdn.jsdeIivr.net/npm/bootstrap@5.0.0-
beta2/dist/css/bootstrap.min.css" reI=”styIesheet"
integrity="sha384-
BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqlj61tLrc4wSX0s
zH/Ev+nYRRuWIoIfIfI" crossorigin="anonymous">
<styIe>
li{
margin-right: 30px;
border:2px solid tomato;
border-radius: 10px;
padding: Spx;
width: 100px;
text-align: center;

a{
text-decoration: none;
color:tomato;
font-weight: bold;

</styIe>
</head>
<body class=”container">
<noscript>You need to enable JavaScript to run this
app.</noscript>
<div id="root"></div>

This HTML file isa template.


If you open it directly in the browser, you will see
an empty page.

You can add webfonts, meta tags, or analytics to


this file.
The build step will place the bundled scripts into
the <body> tag.

To begin the development, run ”npm start” or ”yarn


start”.
To createa production bundle, use ”npm runbuild”
or ”yarn build”.

</body>
</htmI>

Route Parameters
- Route Parameters are used to query any content
in the component directly from URL.
- Route Parameters are used to transport data
across requests.
- Route Parameters are used in the place of query
strings
Syntax:
http://localhost:3200/product?id=1&name=tv
http://localhost:3200/1/tv
- Parameters are configured in <Route>
Syntax:
<Route path=”/product/:param1/:param2”>
</Route>
- Parameters are passed into URL
Syntax:
http://localhost:3200/product/param1val/param
2vaI
- To access the route parameters you can use the
method
“useParams()”

Ex:
AppHome.js
import React from 'react“,
import {BrowserRouter as Router, Redirect, Route,
Switch, useLocation, Link, useParams} from ’react-
router-dom“,

function Home(){
return(
<div>
<h2>Amazon Home</h2>
<p>Shopping Home Page</p>
</div>

function Electronics(){
return(
<div>
<h2>EIectronics Home</h2>
<img src="Images/speaker.jpg" width=”100"
height="100" />
<img src="Images/earpods.jpg" width=”100"
height="100" />
</div>

function Footwear(){
return(
<div>
<h2>Footwear Home</h2>
<img src= Images/shoe.jpg" width="100"
height="100" />
<img src="Images/shoe1.jpg" width="100"
height=II100" />
</div>

function Fashion(){
return(
<div>
<h2>Fashion Home</h2>
<img src="Images/shirt.jpg" width=”100"
height="100" />
<img src="Images/jeans.jpg" width="100"
height="100" />
</div>

function Details(){
let {id, name, price} = useParams();
return(
<div>
<h2>DetaiIs Page</h2>
<dI>
<dt>Product Id</dt>
<dd>{id)</dd>
<dt>Name</dt>
<dd>{name}</dd>
<dt>Price</dt>
<dd>{price}</dd>
</dI>
</div>

function NotFound(){

return(
<div>
<h2>Not-Found</h2>
<p>Page you requested <code>
{window.location.href} </code> - Not Found</p>
<p><Link to="/home">Back to
Home</Link></p>
</div>
export default class AppHome extends
React.Component

render(){
return(
<Router>
<header>
<h 1>Amazon Shopping</h1>
</header>
<div>
<uI style={{dispIay:’flex’, IistStyle:’none’)}>
<Ii><Link to= /home”>Home</Link></Ii>
<Ii><Link
tom/eIectronics Electronics</Link></Ii>
<Ii><Link
to="/footwear">Footwear</Link></Ii>
<Ii><Link
/
tom fashion">Fashion</Link></Ii>
<Ii><Link
tom /detaiIs/1/mobile/56001 Details</Link></Ii>
</uI>
</div>
<hr />
<Switch>
<Route exact path=”/">
<Home />
</Route>
<Route path=”/home">
<Redirect to= /I
</Route>
<Route path="/eIectronics”>
<EIectronics />
</Route>
<Route path=”/footwear”>
<Footwear />
</Route>
<Route path=”/fashion">
<Fashion />
</Route>
<Route path=”/details/:id/:name/:price">
<DetaiIs/>
</Route>
<Route path=”*">
<NotFound />
</Route>
</Switch>
</Router>

Ex: Nested Routes


AppHome.js
import React from 'react",
import {BrowserRouter as Router, Redirect, Route,
Switch, useLocation, Link, useParams} from 'react-
router-dom",

function Home(){
return(
<div>
<h2>Amazon Home</h2>
<p>Shopping Home Page</p>
</div>

function Electronics(){
return(
<div>
<h2>EIectronics Home</h2>
<img src="Images/speaker.jpg" width=”100"
height="100" />
<img src= Images/earpods.jpg" width=”100"
height="100" />
</div>

function Footwear(){
return(
<div>
<h2>Footwear Home</h2>
<img src="Images/shoe.jpg" width="100"
height=II100I
<img src="Images/shoe1.jpg" width="100"
height="100" />
</div>

function Fashion(){
return(
<div>
<h2>Fashion Home</h2>
<img src="Images/shirt.jpg" width=”100"
height="100" />
<img src= Images/jeans.jpg" width="100"
height="100" />
</div>

function Categories(){
let categories =[
{Categoryld: 1, CategoryName: "Electronics"),
{Categoryld: 2, CategoryName: "Footwear")

return(
<div>
<h2>Categories</h2>
<oI>

categories.map(cat =>
<Ii key={cat.CategoryId}><Link
to= /products/' +
cat.CategoryId)>{cat.CategoryName}</Link></Ii>

</oI>
</div>

let products =[
{Productld:1, Name: ’Samsung TV', Price: 45000.33,
Categoryld: 1},
{Productld:2, Name: ’Nike Casuals', Price: 6000.44,
Categoryld: 2},
{Productld:3, Name: ’Earpods’, Price: 3500.44,
Categoryld: 1},
{Productld:4, Name: ’Lee Boot’, Price: 6300.33,
Categoryld: 2}

function Products(){
let (id) = useParams();

let results = products.filter(x=>x.CategoryId==id);


return(
<div>
<h3>Products List</h3>

results.map(prod=>(
<Ii><Link to={’/details/'+
prod.ProductId}>{prod.Name)</Link></Ii>

</oI>
<div>
<Link to="/categories”>Back to
Categories</Link>
</div>
</div>

function Details(){
let {id) = useParams();
let searchedProduct =
products.find(x=>x.ProductId==id);
return(
<div>
<h2>DetaiIs Page</h2>
<dI>
<dt>Name</dt>
<dd>{searchedProduct.Name}</dd>
<dt>Price</dt>
<dd>{searchedProduct.Price}</dd>
<dt>ProductId</dt>
<dd>{searchedProduct.ProductId}</dd>
</dI>
</div>

function NotFound(){

return(
<div>
<h2>Not-Found</h2>
<p>Page you requested <code>
{window.location.href} </code> - Not Found</p>
<p><Link to=”/home">Back to
Home</Link></p>
</div>
export default class AppHome extends
React.Component

render(){
return(
<Router>
<header>
<h1>Amazon Shopping</h1>
</header>
<div>
<uI styIe={{dispIay t flex’, IistStyle:’none')}>
<Ii><Link to="/home”>Home</Link></Ii>
<Ii><Link
to="/eIectronics">EIectronics</Link></Ii>
<Ii><Link
to="/footwear">Footwear</Link></Ii>
<Ii><Link
/
tom fashion">Fashion</Link></Ii>
<Ii><Link
to="/categories">Categories</Link></Ii>
<Ii><Link
tom /detaiIs/1/mobile/56001 Details</Link></Ii>
</uI>
</div>
<hr />
<Switch>
<Route exact path=”/">
<Home />
</Route>
<Route path=”/home">
<Redirect to= /I
</Route>
<Route path="/eIectronics”>
<EIectronics />
</Route>
<Route path=”/footwear”>
<Footwear />
</Route>
<Route path=”/fashion">
<Fashion />
</Route>
<Route path=”/categories">
<Categories />
</Route>
<Route path=”/products/:id">
<Products />
</Route>
<Route path="/details/:id”>
<DetaiIs/>
</Route>
<Route path=”*">
<NotFound />
</Route>
</Switch>
</Router>

Authentication/ Secured Routes


- Application-level security includes
o XSS [Cross Site Scripting Attack]
o Request Forgery
o Authorization/ Authentication

- Authorization is preventing access to resources.


- Authentication is verifying user credentials like
userid, password, security token etc.

Securing React JS Application


- Protection from XSS with Data binding
- Detecting Dangerous URLs
- Rendering HTML
- Direct DOM Access
- Server-side rendering
- Detecting Vulnerabilities in Dependencies
- Injecting JSON state
- Detecting Vulnerable Versions of react.
- Authentication and Authorization

Precautions:
Cross Site Scripting Attack [XSS]
Syntax:
<td>{ productName} </td> // Good
<td innerHTML={productName)> </td> // Bad — XSS

Unsecured URLs
- URL may contain dynamic logic or interaction
Syntax:
<a href=”javascript:function(){}> Text </a>
- URL based script injection
- Use HTTP forunsecured and HTTPS forsecured
- This requires parsing and verifying URL.
- You can use JavaScript “URL()”
Syntax:
function SecurityTest(){
function Hello(){
alert("Hello! React )

return(
<div>
<h2>Security Test</h2>
<button onClick={HeIIo)>Test</button>
// Secured
<a href={”javascript:g{HeIIo)”)>CIick
Here..</a> //Not Secured
</div>
- If you want HTML tousethestring with script then
you have to use “DOM Sanitizer”
- It allows to use the functions safely in DOM HTML
elements.
- It requires “dangerouslySetlnnerHTML” attribute
for DOM element.
- It is defined in the library “dompurify”
Ex:
- Install “dompurify”
> npm install dompurify
- Import dompurify
Import purify from ‘dompurify’
- Use “sanitize()”
function SecurityTest(){
function Hello(){
alert("Hello! React");

return(
<div>
<h2>Security Test</h2>
<button onClick={HeIIo}>Test</button>
<a
href={purify.sanitize(”javascript:g{HeIIo())”))>CIick
Here..</a>
</div>

Syntax:
const msg = “<b>HeIIo</b>”;
<div
dangerouslySetlnnerHTML={purify.sanitize(msg)\></
div>

Ex:
- Install dompurify
> npm install dompurify
- Import dompurify
import purify from ‘dompurify’
- Use DOM purify with sanitize() method
function SecurityTest(){
const msg = ”<b>HeIIo</b>";
return(
<div>
<h2>Security Test</h2>
<div
dangerouslySetlnnerHTML={{ html:purify.sanitize(
msg)}} ></div>
</div>

Cookies in React
- Cookie isa simple text document
- Cookies comprises of client data
- Cookies can be stored
o In browser memory [In Memory]
o In client hard drive [persistent]
- Cookies store client authentication details and re-
use across requests.
- Cookies can be defined with expiry so that they
are deleted automatically after specific duration.
- JavaScript manages cookies by using
o document.cookie
- In React you can use local storage
Note: By default, all cookies are in-memory, to make
them persistent you have to setexpiry for cookie.
Ex:
- Import “usestate”
import React, {usestate} from 'react'
- Createa component
function Login(){
const [message, setMessage] = usestate(");
const CreateCookie = (email) =>{
IocalStorage.setItem(’email’, email);
setMessage("Cookie Created");

return(
<div>
<IabeI>EmaiI :</IabeI>
<input
onChange={(e)=>CreateCookie(e.target.value)}
type="text"/>
<div>
{message}
</div>
</div>

React-Cookie Library
- Install library
> npm install react-cookie
- Import
import {useCookies) from 'react-cookie'
Add function
function Login(){
const [message, setMessage] = usestate(");
const [cookies, setCookie] =
useCookies(['useremaiI’]);

const CreateCookie = (email) =>{


IocalStorage.setItem(’email’, email);
setMessage("Cookie Created");
let now = new Date();
now.setTime(now.getTime()+
(24*60*60*1000));
setCookie(’useremaiI’,email, {path: '/’});

return(
<div>
<IabeI>EmaiI :</IabeI>
<input
onChange={(e)=>CreateCookie(e.target.value)}
type="text"/>
<div>
{message} <br />
{cookies.useremaiI}
</div>
</div>

Authorized Access to Resources


- Secured Routes
- A secured route will verify the credentials and
provide access to any resource location when
authentication passed.
- You can restrict access to certain resources in
application.
- You have to configurea custom router for
authorization.

Ex:
SecurityDemo.js
import React, {usestate, useContext, createContext)
from ’react",
import {BrowserRouter as Router, Route, Switch,
Redirect, useHistory, useLocation, Link) from ’react-
router-dom",
function PublicPage(){
return(
<h2>PubIic Page</h2>

function Protected Page(){


return(
<h2>Protected Page</h2>

const authContext = createContext();

function useAuth(){
return useContext(authContext);

function Login Page(){


let auth = useAuth();
let history = useHistory();
let location = useLocation();
let {from} = location.state| | {from: {pathname: "/"}};
let login = () => {
auth.signin(()=>{
history.replace(from);

return(
<div>
<p>PIease Login to View Protected Page</p>
<button onCIick={Iogin\>Login</button>
</div>

function AuthButton()(
let history = useHistory();
let auth = useAuth();
return auth.user? (<p>WeIcome login success..! {"
"} <button onClick={()=>{auth.signout(()=>
history.push("/”)))} >Logout</button> </p>) (<p>You
are not logged in..Please Login..</p>)

function PrivateRoute({children, ...rest))(


let auth = useAuth();
return(
<Route
{...rest) //path, component
render={ ({location)) => auth.user? (children):
(<Redirect to={{pathname: "/Iogin", state:
{from:location)))/>))

function useProvideAuth(){
const [user, setUser] = useState(null);
const signin = callback =>{
return fakeAuth.signin(()=>{
setUser(”user");
callback();

const signout = callback =>{


return fakeAuth.signout(()=>{
setUser(null);
callback();

return{
user,
signin,
signout

const fakeAuth ={
isAuthenticated false,
signin(callback){
fakeAuth.isAuthenticated = true;
setTimeout(callback, 100);

signout(callback){
fakeAuth.isAuthenticated = false;
setTimeout(callback, 100);

function ProvideAuth({children)){
const auth = useProvideAuth();
return(
<authContext.Provider vaIue={auth)»
{children)
</authContext.Provider>

export default function SecurityDemo(){


return(
<ProvideAuth>
<Router>
<div>
<AuthButton />
</div>
<uI>
<Ii>
<Link to="/public)>PubIic Page</Link>
</Ii>
<Ii>
<Link to="/protected">Protected
Page</Link>
</Ii>
</uI>
<Switch>
<Route path=”/pubIic">
<PubIicPage />
</Route>
<Route path=”/Iogin">
<LoginPage />
</Route>
<PrivateRoute path="/protected">
<ProtectedPage />
</PrivateRoute>
</Switch>
</Router>
</ProvideAuth>

Building Cross Platform Mobile Applications in React


[Progressive Web Applications - PWA]
- You can develop and design app like experience in
browser.
- You can use React Native with Material UI
components.
- You can use frameworks like
o Apache Cordova
o Ionic
o Native Script etc..

Building PWA using Ionic in React:


- Ionic isa framework used to build cross platform
and PWA, which can run on any device.
- It provides pre-defined components and hooks for
React.
- You can use Ionic instead of React Native and
Material UI components.

Download and Install Ionic CLI on your PC:


- CLI is Command Line Tool, which provides set of
commands used to create and manage your
application.
> npm install -g @ionic/cli

Createa new React application integrated with Ionic


Framework
> ionic start appName tabs --type=react

Note: It will createa react application integrated with


ionic framework that provides library of pre-defined
components and UX.
- Unified UX
o Your application will have same behaviour
across all devices
o Mobile users can get access to everything.
o It will not optimize your application.
- Fluid UX
o User will stay on one page and gets access to
everything from the page.
o SPA and PWA
Update your react application to use react hooks and
PWA
> npm install @ionic/react-hooks @ionic/pwa-
elements
[Ionic provides various components derived from
“pwa-elements”]

Note: Ionic react uses “TypeScript” - tsx [.ts]

Setup “CustomElements” from window


- Go to “index.tsx” in “src” folder
- Import and configure “pwa-elements”
import{ defineCustomElements) from ’@ionic/pwa-
elements/loader",
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getEIementById('root')

defineCustomEIements(window);

Run Your React Application with Ionic


> ionic serve

App.tsx is the startup component, you can customize


App.tsx in “src”
import{ Redirect, Route) from 'react-router-dom",
import{
IonApp,
lonlcon,
IonLabel,
IonRouteroutlet,
IonTabBar,
IonTabButton,
IonTabs,
) from '@ionic/react",
import( IonReactRouter) from ’@ionic/react-router",
import{ ellipse, square, triangle, call, images, camera}
from 'ionicons/icons",
import Tab1 from './pages/Tab1",
import Tab2 from './pages/Tab2",
import Tab3 from './pages/Tab3",

/* Core CSS required for Ionic components towork


properly */
import ’@ionic/react/css/core.css",

/* Basic CSS for apps built with Ionic */


import ’@ionic/react/css/normalize.css",
import ’@ionic/react/css/structure.css",
import ionic/react/css/typography.css“,

/* Optional CSS utils that can be commented out*/


import '@ionic/react/css/padding.css",
import ’@ionic/react/css/float-elements.css",
import ’@ionic/react/css/text-alignment.css'
import ’@ionic/react/css/text-transformation.css",
import ’@ionic/react/css/flex-utiIs.css",
import ’@ionic/react/css/display.css",

/* Theme variables */
import ’./theme/variables.css

const App: React.FC = () => (


<IonApp>
<IonReactRouter>
<IonTabs>
<IonRouterOutIet>
<Route exact path="/tab1”>
<Tab1 />
</Route>
<Route exact path="/tab2”>
<Tab2/>
</Route>
<Route path="/tab3”>
<Tab3/>
</Route>
<Route exact path="/">
<Redirect to="/tab1" />
</Route>
</IonRouterOutIet>
<IonTabBar sIot="botto
<IonTabButton tab=”tab1" hrefm /tab1">
<IonIcon icon={call}/>
<IonLabeI>CaII</IonLabeI>
</IonTabButton>
<IonTabButton tab=”tab2" href="/tab2">
<IonIcon icon={camera) />
<IonLabeI>Camera</IonLabeI>
</IonTabButton>
<IonTabButton tab=”tab3" hrefm /tab3">
<IonIcon icon={images}/>
<IonLabeI>GaIIery</IonLabeI>
</IonTabButton>
</IonTabBar>
</IonTabs>
</IonReactRouter>
</IonApp>

export default App;


- Add a new folder “hooks”
- Add a new file into Hooks “usePhotoGaIIery.ts”
import{ useCamera} from '@ionic/react-
hooks/camera",

import{ CameraResultType, CameraSource,


CameraPhoto, Capacitor, FilesystemDirectory} from
'@capacitor/core",

export function usePhotoGallery(){


const{ getPhoto} = useCamera();
const takePhoto = async () => {
const cameraPhoto = await getPhoto({
resultType CameraResuItType.Uri,
source: CameraSource.Camera,
quality: 100
return{
takePhoto

- Go to “tab-2.tsx”
import( IonContent, IonHeader, IonPage, IonTitle,
IonToolbar) from '@ionic/react",
import ExploreContainer from
'../components/ExploreContainer",
import ’./Tab2.css",
import{ usePhotoGallery) from
’../hooks/usePhotoGallery",

const Tab2: React.FC = () => {


const{ takePhoto} = usePhotoGallery();
takePhoto();
return(
<IonPage>
<IonHeader>
<IonTooIbar>
<IonTitIe>Camera</IonTitIe>
</IonTooIbar>
</IonHeader>
<IonContent fuIIscreen>
<IonHeader coIIapse="condense
<IonTooIbar>
<IonTitIe size="Iarge”>Camera</IonTitIe>
</IonTooIbar>
</IonHeader>
<ExpIoreContainer name=”Tab2 page” />
</IonContent>
</IonPage>
)*

export default Tab2;


Material UI
- It provides pre-defined components forreact
application.
- You can customize and inject into application.
- Material UI is similar to bootstrap, but native to
react application.
- More compatible with React application.
- Material UI provides
o Container
o Grid
o Modal
o Accordion
o Alerts etc..
Download and Install Material UI for your React
Application
- Change toyour project folder and run the
following command
> npm install @material-ui/core
- You can also download material icons
> npm install @material-ui/icons

Ex: Card inMaterial-UI


- Material UI provides various components forcard
o <CardHeader>
o <CardMedia>
o <CardContent>
o <CardActions>
o <CoIIapse>
o <Avatar>
- You have to import all the library required for
components
Ex: Card

import React from 'react",


import{ makestyles) from '@material-ui/core/styles",
import clsx from 'clsx",
import Card from '@material-ui/core/Card'
import CardHeader from '@materiaI-
ui/core/CardHeader'
import CardMedia from '@materiaI-
ui/core/CardMedia'
import CardContent from '@materiaI-
ui/core/CardContent'
import CardActions from '@materiaI-
ui/core/CardActions'
import Collapse from ’@material-ui/core/Collapse",
import Avatar from '@material-ui/core/Avatar",
import IconButton from '@materiaI-
ui/core/IconButton",
import Typography from '@materiaI-
ui/core/Typography'
import{ red) from '@material-ui/core/colors',
import Favoritelcon from '@materiaI-
ui/icons/Favorite
import Sharelcon from '@material-ui/icons/Share',
import ExpandMorelcon from '@materiaI-
ui/icons/ExpandMore'
import MoreVertlcon from material-
ui/icons/MoreVert",

const usestyles = makeStyIes((theme) => ({


root:{
maxWidth: 345,

media:{
height: 0,
paddingTop: '56.25Oo',// 16:9

expand:{
transform: 'rotate(0deg)',
marginLeft: 'auto',
transition: theme.transitions.create('transform',{
duration: theme.transitions.duration.shortest,
›),
expandopen:{
transform: 'rotate(180deg)',

avatar:{
backgroundColor: red[500],

export default function RecipeReviewCard(){


const classes = usestyles();
const [expanded, setExpanded] =
React.useState(false);

const handleExpandClick = () => {


setExpanded(!expanded);
return(
<Card className={cIasses.root)>
<CardHeader
avatar=(
<Avatar aria-IabeI="recipe"
className={cIasses.avatar)>
R
</Avatar>

action={
<IconButton aria-label= settings">
<MoreVertIcon />
</IconButton>

titIe="Shrimp and Chorizo Paella"


subheader="September 14,2016”

<CardMedia
className={classes.media}
image="/static/images/cards/paeIIa.jpg
titIe="PaeIIa dish"

<CardContent>
<Typography variant="body2"
coIor=”textSecondary” component=”p">
This impressive paella isa perfect party dish and
a fun meal to cook together with your
guests. Add 1 cup of frozen peas along with the
mussels, if you like.
</Typography>
</CardContent>
<CardActions disabIeSpacing>
<IconButton aria-IabeI=”add to favorites">
<FavoriteIcon />
</IconButton>
<IconButton aria-label=”share">
<ShareIcon />
</IconButton>
<IconButton
className={cIsx(classes.expand,{
[classes.expandOpen]: expanded,
onCIick={handIeExpandCIick}
aria-expanded={expanded}
aria-IabeI=”show more"

<ExpandMoreIcon />
</IconButton>
</CardActions>
<CoIIapse in={expanded) timeout="auto"
unmountOnExit>
<CardContent>
<Typography paragraph>Method:</Typography>
<Typography paragraph>
Heat 1/2 cup ofthe broth ina pot until
simmering, add saffron and set aside for 10
minutes.
</Typography>
<Typography paragraph>
Heat oil ina (14- to 16-inch) paella pan ora
large, deep skillet over medium-high
heat. Add chicken, shrimp and chorizo, and
cook, stirring occasionally until lightly
browned,6 to8 minutes. Transfer shrimp toa
large plate and set aside, leaving chicken
and chorizo in the pan. Add pimentón, bay
leaves, garlic, tomatoes, onion, salt and
pepper, and cook, stirring often until thickened
and fragrant, about 10 minutes. Add
saffron broth and remaining4 1/2 cups chicken
broth; bring toa boil.
</Typography>
<Typography paragraph>
Add rice and stir very gently to distribute. Top
with artichokes and peppers, and cook
without stirring, until most ofthe liquid is
absorbed, 15 to 18 minutes. Reduce heat to
medium-low, add reserved shrimp and mussels,
tucking them down into the rice, and cook
again without stirring, until mussels have
opened and rice is just tender,5 to7
minutes more. (Discard any mussels that don't
open.)
</Typography>
<Typography>
Set aside off of the heat to let rest for 10
minutes, and then serve.
</Typography>
</CardContent>
</Collapse>
</Card>
)*

Ex:Avtar

import React from react",


import{ makestyles} from '@material-ui/core/styles",
import Avatar from '@material-ui/core/Avatar",

const usestyles = makeStyIes((theme) => ({


root:{
display: 'flex',
margin: theme.spacing(1),

l)):

export default function ImageAvatars(){


const classes = usestyles();

return(
<div className={cIasses.root}>
<Avatar aIt="Remy Sharpen
src=”/static/images/avatar/1.jpg" />
<Avatar aIt="Travis Howard”
src=”/static/images/avatar/2.jpg" />
<Avatar alt= Cindy Baker
src=”/static/images/avatar/3.jpg" />
</div>
)
Ex: Dialog

import React from react",


import Button from ’@material-ui/core/Button",
import Dialog from ’@material-ui/core/Dialog",
import DialogActions from '@materiaI-
ui/core/DialogActions",
import DialogContent from '@materiaI-
ui/core/DialogContent",
import DialogContentText from ’@materiaI-
ui/core/DialogContentText",
import DialogTitle from '@materiaI-
ui/core/DialogTitle",

export default function AlertDialog(){


const [open, setopen] = React.useState(false);

const handleClickopen = () => {


setOpen(true);
const handleClose = () => {
setOpen(false);

return(
<div>
<Button variant="outIined" coIor="primary"
onClick={handIeCIickOpen)>
Open alert dialog
</Button>
<DiaIog
open={open)
onCIose={handIeCIose)
aria-IabeIIedby="aIert-dialog-title"
aria-describedby="aIert-dialog-description"

<DiaIogTitIe id=”aIert-dialog-titIe">{"Use Google's


location service?"}</DiaIogTitIe>
<DiaIogContent>
<DiaIogContentText id="aIert-diaIog-
description">
Let Google help apps determine location. This
means sending anonymous location data to
Google, even when no apps are running.
</DiaIogContentText>
</DiaIogContent>
<DiaIogActions>
<Button onCIick={handIeCIose} coIor=”primary
Disagree
</Button>
<Button onCIick={handIeCIose) coIor=”primary”
autoFocus>
Agree
</Button>
</DiaIogActions>
</DiaIog>
</div>
)*

React Native
- It isa cross platform library for building mobile
native applications.
- Unified experience across devices [Unified-UX].
- Android and iOS native applications.
- React native provides native components, which
can run on any device with unified UX.

Core Components ofReact Native

React Android IOS View Web View Descriptio


Native UI View n
Componen

<View> <ViewGrou <UIView> <div> It isa


p> container
that
supports
layout
with
flexbox,
style,
touch
handling
etc.
<Text> <TextView> <UITextView> <p> Display
styles,
strings of
text,
handling
touch
events.
<Image> <ImageView <UIImageVie <img> Displaying
> w> different
types of
images.
<ScroIIView <ScroIIView <UIScroIIView <div> It is
scrollable
container,
overflow
effects
<TextInput <EditText> <UITextFieId> <input Allows
> type=”text text input.

<StyIeSheet CSS
Stylesheet
S
<button>

<Switch>

<FIatList> Scrollable
lists
<SectionLis Sectioned
t> list
<AIert>

<ModaI>

<StatusBar

Install “Expo-CLI” for building React Native


Application
> npm install -g expo-cli

Createa React Native Application


> expo init mobile-shopping
Run Application
C:\mobile-shoppings npm start
[Application starts development environment where
you canchoose the target platform]

Syntax: React Native Component


Header.js
import React from “react”;
import {StyleSheet, View, Text} from ‘react-native’;
const styles = StyIeSheet.create({
header:{

headerTitle:{

const Header = props =>{


return(
<View style={styIes.header)>
<Text style={styles.headerTitle}> {props.title)
</Text>
</View>

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy