Reactjs by Sudhakar Sir
Reactjs by Sudhakar Sir
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
React JS is library
Angular is Framework
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.
React Workspace
- It comprises of shared libraries for all your ReactJS
projects.
- In workspace you can maintain multiple projects
- Workspace comprises of
"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"
</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>
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')
)*
<!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.
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
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;
Price:number;
Stock:boolean;
Total():number;
Print():void;
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
Ex:
interface ProductName{
abstract function PrintName():void;
abstract class ProductPrice
function PrintPrice():void{
log "Price = 45000";
class Main{
static function main(args: string[]): void{
var tv = new Product();
tv.PrintName();
tv.PrintPrice();
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
hello();
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
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”
ReactDOM.render(
element,
document.getEIementById('root')
Ex:
const element =(
<div>
<h2> Welcome </h2>
</div>
)
Ex: Invalid
const element =(
<h1> Amazon </h1>
V
<p> Online Shopping
)*
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:
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
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>
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>
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'
Ex:
const element =(
<div className='container'>
<h2 align='center’>React JS EIements</h2>
</div>
ReactDOM.render(
element,
document.getEIementById('root’)
Ex:
App.js
const element =(
<div className='container'>
<h2 align='center’>WeIcome to React JS</h2>
</div>
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.
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
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(
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>
- 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
Ex:
App.js
function template(){
return "React JS Class Component";
render(){
return <h2 aIign="center">{tempIate())</h2>;
ReactDOM.render(
<Login />,
document.getEIementById('root')
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.
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>
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')
render(){
return(
<header cIassName="bg-danger text-white text-
center">
<h1>Amazon Shopping</h1>
</header>
render(){
return(
<nav>
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>
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>
<Header />
<section>
<div className= row
<div className="coI-3">
<MenuContent />
</div>
<div className="coI-9">
<Products />
</div>
</div>
</section>
<footer className="text-center">
© 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>
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.
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'
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>
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>
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: 'Shirt',
price: 2000.33,
photo: 'shirt.jpg'
name: 'Earpods’,
price: 4500.55,
photo: 'earpods.jpg’
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>
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>
</head>
<body>
<div id= root
</div>
</body>
</htmI>
Ex:
App.js
const products =[
name: Shirt
price: 2000.33,
photo: 'shirt.jpg’
name: 'Earpods’,
price: 4500.55,
photo: 'earpods.jpg’
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>
render(){
return(
<div className="container-fIuid">
<h1 className="text-center">Products
CataIog</h1>
<Product />
</div>
ReactDOM.render(
<MainContent />,
document.getEIementById(’root')
Task:
const products =[
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.
constructor(){
//define the state object.
render(){}
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>
render(){
return(
<div className="container-fIuid">
<Product />
</div>
ReactDOM.render(
<MainContent />,
document.getEIementById(’root')
)/
constructor(props){
super(props);
this.state ={
data [
constructor(props){
super(props);
this.state ={
data [
render(){
return(
<div className="container-fIuid">
<h2>Products CataIog</h2>
<Product />
</div>
ReactDOM.render(
<MainContent />,
document.getEIementById(’root')
)/
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 [
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>
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)
Ex:
App.js
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)
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.
Ex:
App.js
const headingstyle ={
backgroundColor: ’darkcyan',
color: 'white’,
textAlign: ’center’,
padding: ’Spx',
marginTop: '10px’
</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.
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')
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>
render(){
return(
<div className="container-fIuid">
<h3>Event HandIing</h3>
<Product />
</div>
ReactDOM.render(
<MainContent />,
document.getEIementById (moot')
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>
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
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>
render(){
return(
<div className="container-fIuid">
<h3>Event HandIing</h3>
<Product />
</div>
ReactDOM.render(
<MainContent />,
document.getEIementById (moot')
super();
this.state ={ );
this.eventHandIer
this.eventHandler.bind(this);
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>
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
<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>
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>
render(){
return(
<div className="container-fIuid">
<h3>Event HandIing</h3>
<Product />
</div>
ReactDOM.render(
<MainContent />,
document.getEIementById('root')
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')
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>
render(){
return(
<div className="container-fIuid">
<h3>Event HandIing</h3>
<Product />
</div>
ReactDOM.render(
<MainContent />,
document.getEIementById('root')
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>
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.
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>
render(){
return(
<div className="container-fIuid">
<h3>Event HandIing</h3>
<Product />
</div>
ReactDOM.render(
<MainContent />,
document.getEIementById('root')
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>
render(){
return(
<div className="container-fIuid">
<h3>Event HandIing</h3>
<Product />
</div>
ReactDOM.render(
<MainContent />,
document.getEIementById('root')
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
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]
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>
render(){
return(
<div className="container-fIuid">
<h3>Event HandIing</h3>
<Register />
</div>
ReactDOM.render(
<MainContent />,
document.getEIementById('root')
VerifyChar(e){
if(e.key=="y”){
location.href=”http://www.amazon.in”;
) else{
document.write("Action Canceled..");
render(){
return(
render(){
return(
<div className="container-fIuid">
<h3>Event HandIing</h3>
<Register />
</div>
ReactDOM.render(
<MainContent />,
document.getEIementById('root')
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>
render(){
return(
<div className="container-fIuid">
<h3>Event HandIing</h3>
<Register/>
</div>
ReactDOM.render(
<MainContent />,
document.getEIementById('root')
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>
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>
render(){
return(
<div className="container-fIuid">
<h3>Event HandIing</h3>
<MouseDemo />
</div>
ReactDOM.render(
<MainContent />,
document.getEIementById(’root')
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>
render(){
return(
<div className="container-fIuid">
<h3>Event HandIing</h3>
<MouseDemo />
</div>
ReactDOM.render(
<MainContent />,
document.getEIementById(moot')
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”
</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')
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>
render(){
return(
<div className="container-fIuid">
<h3>Event HandIing</h3>
<EventsDemo />
</div>
ReactDOM.render(
<MainContent />,
document.getEIementById('root')
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>
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')
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>
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.
- 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
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>
render(){
return(
<div className="container-fIuid">
<TouchEvent/>
</div>
ReactDOM.render(
<MainContent />,
document.getEIementById('root')
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')
function LoginSuccess(props){
return <h2>Login Success..</h2>
function LoginFaiIure(props){
return <h2>Login Failed..</h2>
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’)
function DisplayView()(
return(
<div>
Price <IabeI></IabeI>
<button>Edit</button>
</div>
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 />
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')
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')
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>
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” ?:
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>
ReactDOM.render(
<MainContent/>,
document.getEIementById('root')
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: ₹ 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>
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>
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
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>
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>
componentWillMount(){
alert(”Error Component Requested");
componentDidMount(){
alert(”Error Component Mounted..");
componentWillUnmount()(
alert(”Error Disposed..");
render(){
return(
<h2>InvaIid Password</h2>
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>
ReactDOM.render(
<MainContent/>,
document.getEIementById('root')
MongoDB Terminology:
RDBMS MongoDB
Database Database
Table Collection
Records/ Rows Documents
Field Field
Joins Embedded Documents
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}])
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");
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
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')
)*
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>
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]
Shorthand Requests
axios.get(url)
axios.post(url, data[])
axios.put()
axios.delete()
then(response=>{
console.log(‘First URL’, response[0].data),
console.log(‘SecondURL’, response[1].data)
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’);
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>
app.listen(8080);
console.log(“Server Started: http://127.0.0.1:8080”);
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
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",
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>
Ex:
import React from ’react",
import {useFormik) from 'formik",
const FormLibraryDemo =() =>{
const formik = useFormik({
initialValues:{
Productld: ",
Name: ",
Price:
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>
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;
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")
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()
Ex:
YupVaIidationDemo.js
import React from react“,
import {useFormik} from 'formik",
import* as yup from ’yup",
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>
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>
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",
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”)
Routing Architecture:
Ex:
AppHome.js
import React from ’react“,
import{ BrowserRouter as Router, Route) from 'react-
router-dom",
render(){
return(
<Router>
<Route path=”/" component=(Home) />
<Route path=”/contact" component={Contact) />
</Router>
Ex:
AppHome.js
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
function Footwear(){
return(
<div>
<h2>Footwear Home</h2>
<img src="Images/shoe.jpg" width="100"
II I
height= 100
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>
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” />
<Iink reI="manifest"
hrefm''OoPUBLIC_URL Oo/ITlanifest.json
<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>
</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>
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();
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>
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’]);
return(
<div>
<IabeI>EmaiI :</IabeI>
<input
onChange={(e)=>CreateCookie(e.target.value)}
type="text"/>
<div>
{message} <br />
{cookies.useremaiI}
</div>
</div>
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 useAuth(){
return useContext(authContext);
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 useProvideAuth(){
const [user, setUser] = useState(null);
const signin = callback =>{
return fakeAuth.signin(()=>{
setUser(”user");
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>
defineCustomEIements(window);
/* Theme variables */
import ’./theme/variables.css
- 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",
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],
action={
<IconButton aria-label= settings">
<MoreVertIcon />
</IconButton>
<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
l)):
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
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"
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.
<StyIeSheet CSS
Stylesheet
S
<button>
<Switch>
<FIatList> Scrollable
lists
<SectionLis Sectioned
t> list
<AIert>
<ModaI>
<StatusBar
headerTitle:{