React Notes
React Notes
React Notes
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 the user
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 is a 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
<div id="root">
</div>
</body>
</html>
Note: The MIME type of React JS “JSX” script must be
“text/jsx” or “text/babel”
Syntax:
<script type=”text/jsx”> </script>
<script type=”text/babel”></script>
Embedded Component:
- In embedded technique the component is
designed in the page.
- It is faster in access.
- It reduces the load time.
- It reduces the number of requests made to page.
- Code reusability issues
- Extensibility issues
- Maintainability and testability are the issues.
Module Technique:
- Component is designed in a separate JavaScript file
“.js”
- JavaScript file is considered as a 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 of requests made to page and also the
page load time.
Ex:
- Go to “src” folder and add a new file “hello.js”
- Add the following code into “hello.js”
ReactDOM.render(
<p>Welcome to React JS - External
Component</p>,
document.getElementById('root')
);
<!DOCTYPE html>
<html>
<head>
<title>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-d
om.development.js"></script>
<script crossorigin
src="https://unpkg.com/@babel/standalone/babel.
min.js"></script>
<script type="text/jsx"
src="../src/hello.js"></script>
</head>
<body>
<h2>HTML React App</h2>
<div id="root">
</div>
</body>
</html>
JSX
- JSX is a statically-typed, object-oriented
programming language.
- It compiles to standalone JavaScript.
- It can use all feature of JavaScript.
- It finally compiles to JavaScript.
- It is a 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 at the
compile time then it is known as statically typed.
- Dynamically typed is determined during run time.
JSX Operators
JSX Expression
JSX Statements
JSX functions
JSX Classes
JSX Modules
JSX OOPS
Contracts in OOP:
- A contract defines rules for designing any
component.
- Contracts are specified by using “interface”.
- Interface can contain only rules.
- It must have only declaration not implementation.
Syntax:
interface InterfaceName
{
Name : string; // valid
Price : number = 45600.55; // invalid – rules
can’t have implementation
}
- Interface can also define function declaration,
which is implemented later.
- Interface functions can’t have definition.
Ex:
interface IProduct
{
Name:string;
Price:number;
Stock:boolean;
Total():number;
Print():void;
}
- Every rule defined in contract is mandatory to
implement.
- You can’t define any new implementation if it is
not in contract.
JSX Class
- Class is a program template.
- Class is used as entity, model or template.
- Class comprises of data and logic.
- JSX class have following characteristics.
o All JSX classes are derived from a base class
“Object”.
o Object is a 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 any method in
class is abstract.
final It declares that the calls may not
be extended.
- JSX class can contain
o Member Variables and
o Member Functions
Ex:
class Product
{
var _name : String; 🡪 Variable
function constructor(name: string){ 🡪
Constructor Member Function
this._name = name;
}
function Print(): void { 🡪 Member
Function
log "Product Name : " + this._name;
}
}
- Class variable in JSX can be defined with var, const,
and let.
o Member variable in a JSX class can be defined
with
▪ abstract : If a variable is using expression,
which needs implementation.
▪ static : It uses continuous memory.
- Class member function in JSX can be defined with
following attributes
Function Description
Attribute
abstract It declares that the function
should be overridden by a class
that extends the current class.
final It declares that function may not
be overridden.
static It declares that function is static.
It uses continuous memory.
override It declares that the definition of
the function is overriding and
definition is extending.
Ex:
interface ProductName {
abstract function PrintName():void;
}
abstract class ProductPrice
{
function PrintPrice():void {
log "Price = 45000";
}
}
class Product extends ProductPrice implements
ProductName {
override function PrintName():void {
log "Name = Samsung TV";
}
}
class _Main {
static function main(args: string[]): void {
var tv = new Product();
tv.PrintName();
tv.PrintPrice();
}
}
Functions and Closures in JSX
- JSX supports all JavaScript functions and their
manipulations.
- Functions with parameters.
- Function with rest parameters.
Ex:
function PrintList(...list){
for(var item of list) {
document.write(item + "<br>");
}
}
PrintList("Samsung TV","Mobile","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
{
var userName = "Hello ! John";
function constructor(){
var hello = function():void {
log this.userName;
};
hello();
}
static function main(args: string[]):void {
var obj = new _Main();
}
}
JSX Modules
- JavaScript module systems are “Common JS, AMD
[Asynchronous Module Distribution]” etc.
- Module comprises of set of classed which are
exported and imported into another library.
- JSX provide built-in modules to handle various
interactions.
o timer.jsx
o js/web.jsx etc.
- JSX also allows to create and configure custom
modules to build library for react application.
Ex:
import "timer.jsx";
class _Main
{
static function main(args: string[]):void {
Timer.setTimeout(function():void {
log "Hello ! JSX";
}, 2000);
Timer.setTimeout(function():void{
log "Welcome to JSX";
}, 5000);
}
}
Summary
- Variables
- Data Types
- Operators
- Statements
- Interface
- Class
- Member Variables
- Member Functions
- Modules
JSX with React JS
- JSX will allow to configure any expression and store
in a 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 JSX variables 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 add a new file “app.js”
- Add following code into “app.js”
ReactDOM.render(
element,
document.getElementById('root')
);
Ex:
const element = (
<div>
<h2> Welcome </h2>
</div>
);
Ex: Invalid
const element = (
<h1> Amazon </h1>
<p> Online Shopping </p>
);
You can’t have individual elements in “( )” all must be
enclosed in one element.
Ex: Valid
const element = (
<div>
<h1> Amazon </h1>
<p> Online Shopping </p>
</div>
);
- Adding an additional container for multi lines my
effect the hierarchy of your DOM.
- You can use an empty element representation.
“
<> starting
</> ending
“
Ex: Best Technique
const element = (
<>
<h1> Amazon </h1>
<p> Online Shopping </p>
</>
);
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>Online Shopping Site</p>
<img src={pic} />
</>
);
ReactDOM.render(
element,
document.getElementById('root')
);
Index.html
<!DOCTYPE html>
<html>
<head>
<title>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-do
m.development.js"></script>
<script crossorigin
src="https://unpkg.com/@babel/standalone/babel.min
.js"></script>
<script type="text/jsx" src="../src/app.js"></script>
</head>
<body>
<div id="root">
</div>
</body>
</html>
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 for Tags Used for Elements
<img src> :src is attribute
Var pic = new Image();
pic.src= “” : src is property
Ex:
App.js
const pic = 'shoe.jpg';
const element = React.createElement(
'div',
{className: 'container', align: 'center'},
'Welcome to React JS'
)
ReactDOM.render(
element,
document.getElementById('root')
);
Index.html
<!DOCTYPE html>
<html>
<head>
<title>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-d
om.development.js"></script>
<script crossorigin
src="https://unpkg.com/@babel/standalone/babel.
min.js"></script>
<script type="text/jsx"
src="../src/app.js"></script>
<style>
.container {
width: 400px;
height: 200px;
border:2px solid darkcyan;
box-shadow: 3px 4px 5px darkcyan;
border-radius: 20px;
padding: 20px;
}
</style>
</head>
<body>
<div id="root">
</div>
</body>
</html>
</div>
</body>
</html>
You can configure elements in Object Style
- You can use JavaScript object type to configure
elements and render into React Virtual DOM.
- Object comprises of Key and value.
- The keys required for designing element
o type : It defines the element type
o props : It defines the properties [object].
Properties will allow all JS properties.
Ex:
const element = {
type: 'div',
props : {
className: 'container',
children: 'Welcome to React'
}
};
Rendering the Elements
- The elements configured for React are rendered
into “Virtual DOM”.
- The “ReactDOM” method “render()” is used to
create a virtual DOM and render your element into
the DOM.
Syntax:
ReactDOM.render(What [element],
Where[Target]) : It is rendering element into
virtual DOM.
- ElementName: Specifies the element to render.
- Target Container: Specifies the id of element
where the resulting markup must be rendered.
Ex:
const element = (
<div className='container'>
<h2 align='center'>React JS Elements</h2>
</div>
);
ReactDOM.render(
element,
document.getElementById('root')
);
- You can use a Query Selector of JavaScript to
access the element by id and use for rendering
the React element into virtual DOM.
Ex:
App.js
const element = (
<div className='container'>
<h2 align='center'>Welcome to React JS</h2>
</div>
);
const target = document.querySelector('#root');
ReactDOM.render(element, target);
Ex:
App.js
const element = (
<div className='container'>
<h2 align='center'>Hello ! React JS</h2>
</div>
);
const target = document.getElementById('root');
ReactDOM.render(element, target);
React JS Components
- Components are the building blocks of any
React application.
- Typically, a react application is built with
components.
- Component is built with UI and logic as a
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 are designed by using
JavaScript functions and classes.
- Technically a component is React JS can be
o JavaScript function
o JavaScript Class
Functional Components
- The components designed by using JavaScript
functions are known as Functional Components.
- Every functional component is by default
anonymous type in memory.
Syntax:
function()
{
// content to render.
}
- Anonymous function requires a reference name to
access.
Syntax:
const f1 = function() { };
- You can render the functional component into
Virtual DOM by using the reference as “element”
Syntax:
<f1 />
- DOM allows only an element, hence the functional
component is configured as element.
Note:
- The custom components must not collide with
HTML DOM elements.
- The component name must not be the same as
HTML DOM element.
- Every component must follow “PascalCase or
lowercase” in naming.
- Lowercase is suggested only for elements in
browser.
- PascalCase is suggested for component in React to
render in virtual DOM.
- Pascal Case: Every word first letter must be a
capital letter.
Ex:
App.js
const Titletext = () => <h2>Welcome to React JS</h2>;
ReactDOM.render(
<Titletext />,
document.getElementById('root')
);
Index.html
<!DOCTYPE html>
<html>
<head>
<title>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-do
m.development.js"></script>
<script crossorigin
src="https://unpkg.com/@babel/standalone/babel.min
.js"></script>
<script type="text/jsx" src="../src/app.js"></script>
</head>
<body>
<div id="root">
</div>
</body>
</html>
Ex:
App.js
const titleText = "User Login";
const Login = () => (
<>
<h3 align="center">{titleText}</h3>
<dl>
<dt>User Name</dt>
<dd><input type="text" className="form-control"
/></dd>
<dt>Password</dt>
<dd><input type="password"
className="form-control" /></dd>
</dl>
<button className="btn btn-primary
btn-block">Login</button>
</>
);
ReactDOM.render(
<Login />,
document.getElementById('root')
);
Index.html
<!DOCTYPE html>
<html>
<head>
<title>HTML React App</title>
<link rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/di
st/css/bootstrap.min.css"
integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uI
Kz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2"
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-do
m.development.js"></script>
<script crossorigin
src="https://unpkg.com/@babel/standalone/babel.min
.js"></script>
<script type="text/jsx" src="../src/app.js"></script>
<style>
div {
margin-top: 40px;
margin-left: 300px;
justify-content: center;
align-items: center;
padding: 10px;
border:2px solid darkcyan;
border-radius: 20px;
width: 300px;
}
</style>
</head>
<body>
<div id="root">
</div>
</body>
</html>
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 as a JavaScript Class that
extends “React.Component” base class.
Ex:
class Login 🡪 Not a component class
{
}
class Login extends React.Component 🡪
Component class
{
}
- React.Component base class provides “render()”,
which you have to implement in your component
class.
Syntax:
class Login extends React.Component
{
render() {
return “JSX”;
}
}
- Class component is accessed and rendered as
element into Virtual DOM.
Syntax:
ReactDOM.render(
<Login />,
document.getElementById('root')
);
Ex:
App.js
class Login extends React.Component
{
render(){
return (
<>
<h3 align="center">User Login</h3>
<dl>
<dt>User Name</dt>
<dd><input type="text" className="form-control"
/></dd>
<dt>Password</dt>
<dd><input type="password"
className="form-control" /></dd>
</dl>
<button className="btn btn-primary
btn-block">Login</button>
</>
);
}
}
ReactDOM.render(
<Login />,
document.getElementById('root')
);
Index.html
<!DOCTYPE html>
<html>
<head>
<title>HTML React App</title>
<link rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/di
st/css/bootstrap.min.css"
integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uI
Kz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2"
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-do
m.development.js"></script>
<script crossorigin
src="https://unpkg.com/@babel/standalone/babel.min
.js"></script>
<script type="text/jsx" src="../src/app.js"></script>
<style>
div {
margin-top: 40px;
margin-left: 300px;
justify-content: center;
align-items: center;
padding: 10px;
border:2px solid darkcyan;
border-radius: 20px;
width: 300px;
}
</style>
</head>
<body>
<div id="root">
</div>
</body>
</html>
- Property is mutable
- It is defined in class.
- It is accessible within the class by using “this”
keyword.
Ex:
App.js
var copyright = "copyright 2021"; // variable
class Login extends React.Component
{
heading = "User Login"; // property
render(){
return (
<>
<h3 align="center"> {this.heading} </h3>
<dl>
<dt>User Name</dt>
<dd><input type="text" className="form-control"
/></dd>
<dt>Password</dt>
<dd><input type="password"
className="form-control" /></dd>
</dl>
<button className="btn btn-primary
btn-block">Login</button>
<p align="center"><i>{copyright}</i></p>
</>
);
}
}
ReactDOM.render(
<Login />,
document.getElementById('root')
);
Ex:
App.js
function template(){
return "React JS Class Component";
}
class Login extends React.Component
{
render(){
return <h2 align="center">{template()}</h2>;
}
}
ReactDOM.render(
<Login />,
document.getElementById('root')
);
Functional Component vs Class Component
Functional Component
- Functional Components are referred as “Stateless”
[dumb, presentational]
- Functional because they are designed using a
JavaScript function.
- Stateless because they don’t hold or manage state.
- It is difficult for transporting data from one
component to another.
- It uses lot of round trips.
- It will be slow in access.
- It is more secured.
- It manages the memory.
- Tightly coupled.
- No easy to extend.
Class Component
- It is referred as “Stateful”
- Class of ES6
- It comprises of logic and data.
- It can hold and manage memory
- It is good for transporting data across components.
- It can have local state.
- It is not just a class but a container with
constructor, properties, methods, accessors.
- Loosely coupled.
- Easy to extend.
- Maintainability and Testability.
Properties in Component
[React Props]
- A component can accept properties.
- So that component can customize the content that
it is going to return.
- It allows the component to change 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 are read-only.
- Property can’t be modified [its name, structure]
but its value can change.
};
props – can be any type: string, number, boolean,
object, array etc.
- The props of functional component are accessed
by using attribute reference.
Syntax:
<hello propertyName=”{propertyValue}” />
- Every property passed into a component have to
handle “Key and Value”
- Key refers to the property name
- Value refers to the value to store under specific
property name.
- The props that you define can handle any type of
data but in a “object” form.
Syntax:
const hello = obj => <h2> {obj.PropertyName} </h2>;
<hello PropertyName={‘Value’} />
Ex:
App.js
const Product = obj => (
<div className="card">
<div className="card-header">
<h3>{obj.Name}</h3>
</div>
<div className="card-body">
<img src={obj.Photo} width="50%"
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.getElementById('root')
);
Index.html
<!DOCTYPE html>
<html>
<head>
<title>HTML React App</title>
<link rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/di
st/css/bootstrap.min.css"
integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uI
Kz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2"
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-do
m.development.js"></script>
<script crossorigin
src="https://unpkg.com/@babel/standalone/babel.min
.js"></script>
<script type="text/jsx" src="../src/app.js"></script>
<style>
</style>
</head>
<body>
<div id="root">
</div>
</body>
</html>
</style>
</head>
<body>
<div id="root">
</div>
</body>
</html>
- In order to modify the property value of class you
need to create a “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.getElementById('root')
);
Index.html
<!DOCTYPE html>
<html>
<head>
<title>HTML React App</title>
<link rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/di
st/css/bootstrap.min.css"
integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uI
Kz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2"
crossorigin="anonymous">
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/font-aweso
me/4.7.0/css/font-awesome.min.css"
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-do
m.development.js"></script>
<script crossorigin
src="https://unpkg.com/@babel/standalone/babel.min
.js"></script>
<script type="text/jsx" src="../src/app.js"></script>
<style>
section {
height: 600px;
}
footer {
background-color: maroon;
color:white;
}
ul{
list-style: none;
}
li {
border:1px solid maroon;
background-color: maroon;
padding: 4px;
margin-top: 10px;
border-radius: 10px;
width: 200px;
color: white;
font-size: 30px;
}
</style>
</head>
<body>
<div id="root">
</div>
</body>
</html>
Task: Design the above example with functional
components
Ex:
App.js
const Nav = () =>
<nav className="navbar navbar-expand-lg
navbar-dark bg-dark">
<button className="navbar-toggler"
type="button"
data-toggle="collapse"
data-target="#NavMenu">
<span className="navbar-toggler-icon"></span>
</button>
<a href="#" className="navbar-brand">
Amazon Shopping
</a>
<div className="collapse navbar-collapse"
id="NavMenu">
<ul className="navbar-nav">
<li className="nav-item">
<a className="nav-link" href="#">Home</a>
</li>
<li className="nav-item">
<a className="nav-link"
href="#">Electronics</a>
</li>
<li className="nav-item">
<a className="nav-link"
href="#">Footwear</a>
</li>
<li className="nav-item">
<a className="nav-link" data-toggle="modal"
href="#login">Login</a>
</li>
<li className="nav-item">
<SearchBox />
</li>
</ul>
</div>
</nav>
ReactDOM.render(
<MainContent />,
document.getElementById('root')
);
Index.html
<!DOCTYPE html>
<html>
<head>
<title>HTML React App</title>
<link rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/di
st/css/bootstrap.min.css"
integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uI
Kz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2"
crossorigin="anonymous">
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/font-aweso
me/4.7.0/css/font-awesome.min.css"
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-do
m.development.js"></script>
<script crossorigin
src="https://unpkg.com/@babel/standalone/babel.min
.js"></script>
<script
src="https://code.jquery.com/jquery-3.5.1.slim.min.js"
integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OG
pamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"
crossorigin="anonymous"></script>
<script
src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dis
t/js/bootstrap.bundle.min.js"
integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26Lr
Z/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx"
crossorigin="anonymous"></script>
<script type="text/jsx" src="../src/app.js"></script>
</head>
<body>
<div id="root">
</div>
</body>
</html>
Data in React Component
[Data-Driven Components]
- Data for component comes from a service.
- JavaScript based libraries or frameworks usually
handle data by using
o Object
o Array
o Map
- Object: Represents a pseudo class with set of
properties and methods.
- Map: Represents a collection with key and value
references.
- Array: Represents a collection of values stored in
sequential order.
FAQ: What is difference between Map and Object?
Object Map
- Contains default keys - No default keys
- Can’t know the count - Can know the length
of keys of count.
- Object requires an - Map is an iterator.
iterator to read keys
and value.
Ex:
<script>
var products = [
{Name: "TV", Price: 45000.55},
{Name: "Mobile", Price: 33000.44},
{Name: "Shirt", Price: 3100.33}
];
function GetDetails(product) {
var details = `${product.Name} -
${product.Price}<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 GetDetails(product) {
return product.Price >= 30000;
}
function PrintDetails(){
var result = products.filter(GetDetails);
for(var item of result) {
document.write(`${item.Name} - ${item.Price}
<br>`);
}
}
PrintDetails();
</script>
React Component with Data
[Data Driven Component]
- Data for component is provided by properties.
[props]
- In order to define data for any component you
have to configure properties.
- You can’t directly use the local values of module.
- You can access data from local object of module or
from the property of another class by using
“aggregation” [Object-to-Object] communication.
[Has-A-Relation]
Ex:
App.js
var speaker = {
name: 'JBL Speaker',
price: 6000.55,
photo: 'speaker.jpg',
mdf: new Date()
};
class Category
{
CategoryName = 'Electronics'
}
class Product extends React.Component
{
product = speaker;
render(){
const category = new Category();
return (
<div className="card">
<div className="card-header">
<h3>{this.product.name}</h3>
</div>
<div className="card-body">
<img src={this.product.photo} width="200"
height="200" />
</div>
<div className="card-footer">
<h3>{this.product.price}</h3>
<p>{this.product.mdf.toLocaleDateString()}</p>
<p>{category.CategoryName}</p>
</div>
</div>
)
}
}
class MainContent extends React.Component
{
render(){
return (
<>
<Product />
</>
)
}
}
ReactDOM.render(
<MainContent />,
document.getElementById('root')
);
Index.html
<!DOCTYPE html>
<html>
<head>
<title>HTML React App</title>
<link rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/di
st/css/bootstrap.min.css"
integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uI
Kz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2"
crossorigin="anonymous">
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/font-aweso
me/4.7.0/css/font-awesome.min.css"
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-do
m.development.js"></script>
<script crossorigin
src="https://unpkg.com/@babel/standalone/babel.min
.js"></script>
<script
src="https://code.jquery.com/jquery-3.5.1.slim.min.js"
integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OG
pamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"
crossorigin="anonymous"></script>
<script
src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dis
t/js/bootstrap.bundle.min.js"
integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26Lr
Z/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx"
crossorigin="anonymous"></script>
<script type="text/jsx" src="../src/app.js"></script>
</head>
<body>
<div id="root">
</div>
</body>
</html>
ReactDOM.render(
<MainContent />,
document.getElementById('root')
);
Index.html
<!DOCTYPE html>
<html>
<head>
<title>HTML React App</title>
<link rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/di
st/css/bootstrap.min.css"
integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uI
Kz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2"
crossorigin="anonymous">
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/font-aweso
me/4.7.0/css/font-awesome.min.css"
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-do
m.development.js"></script>
<script crossorigin
src="https://unpkg.com/@babel/standalone/babel.min
.js"></script>
<script
src="https://code.jquery.com/jquery-3.5.1.slim.min.js"
integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OG
pamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"
crossorigin="anonymous"></script>
<script
src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dis
t/js/bootstrap.bundle.min.js"
integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26Lr
Z/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx"
crossorigin="anonymous"></script>
<script type="text/jsx" src="../src/app.js"></script>
</head>
<body>
<div id="root">
</div>
</body>
</html>
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: "JBL Speaker",
price: 4500.55,
photo: 'speaker.jpg'
},
{
name: 'Nike Casuals',
price: 6000.55,
photo: 'shoe.jpg'
},
{
name: 'Shirt',
price: 2000.33,
photo: 'shirt.jpg'
},
{
name: 'Earpods',
price: 4500.55,
photo: 'earpods.jpg'
}
];
ReactDOM.render(
<MainContent />,
document.getElementById('root')
);
Index.html
<!DOCTYPE html>
<html>
<head>
<title>HTML React App</title>
<link rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/di
st/css/bootstrap.min.css"
integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uI
Kz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2"
crossorigin="anonymous">
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/font-aweso
me/4.7.0/css/font-awesome.min.css"
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-do
m.development.js"></script>
<script crossorigin
src="https://unpkg.com/@babel/standalone/babel.min
.js"></script>
<script
src="https://code.jquery.com/jquery-3.5.1.slim.min.js"
integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OG
pamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"
crossorigin="anonymous"></script>
<script
src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dis
t/js/bootstrap.bundle.min.js"
integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26Lr
Z/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx"
crossorigin="anonymous"></script>
<script type="text/jsx" src="../src/app.js"></script>
</head>
<body>
<div id="root">
</div>
</body>
</html>
Ex:
App.js
const products = [
{
name: "JBL Speaker",
price: 4500.55,
photo: 'speaker.jpg'
},
{
name: 'Nike Casuals',
price: 6000.55,
photo: 'shoe.jpg'
},
{
name: 'Shirt',
price: 2000.33,
photo: 'shirt.jpg'
},
{
name: 'Earpods',
price: 4500.55,
photo: 'earpods.jpg'
}
];
class Product extends React.Component
{
productsData = products;
render(){
return(
<table className="table table-hover">
<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"
height="100" />
</td>
</tr>
)
})
}
</tbody>
</table>
)
}
}
ReactDOM.render(
<MainContent />,
document.getElementById('root')
);
Task:
const products = [
{
name: "JBL Speaker",
price: 4500.55,
photo: 'speaker.jpg',
description: [
{
Mfd : Date(“2020-10-20”),
Features: “some description”
}
]
},
{
name: 'Nike Casuals',
price: 6000.55,
photo: 'shoe.jpg',
description: [
{
Mfd : Date(“2020-10-20”),
Features: “some description”
}
]
},
{
name: 'Shirt',
price: 2000.33,
photo: 'shirt.jpg',
description: [
{
Mfd : Date(“2020-10-20”),
Features: “some description”
}
]
},
{
name: 'Earpods',
price: 4500.55,
photo: 'earpods.jpg',
description: [
{
Mfd : Date(“2020-10-20”),
Features: “some description”
}
]
}
];
State in React
- Web application uses “HTTP”
- HTTP is a state less protocol.
- It uses the mechanism “Go-Get-Forget”
GO : It establishes connection with server.
GET : It gets response for the request.
FORGET : It cleans up everything. [Removes all
traces of current request]
- Stateless nature of HTTP is an advantage for web
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 are stateful
- React JS “Component” base class
[React.Component] provides a state object that
handle data for application.
Ex:
App.js
class Product extends React.Component
{
product = {
name: 'LG Mobile',
price: 44000.44
};
constructor() {
super();
this.state = {
name: 'JBL Speaker',
price: 4500.55
}
}
render(){
return (
<dl>
<dt>Name</dt>
<dd>{this.state.name}</dd>
<dt>Price</dt>
<dd>{this.state.price}</dd>
<dt>Mobile</dt>
<dd>{this.product.name}</dd>
<dt>Price</dt>
<dd>{this.product.price}</dd>
</dl>
)
}
}
ReactDOM.render(
<MainContent />,
document.getElementById('root')
);
ReactDOM.render(
<MainContent />,
document.getElementById('root')
);
ReactDOM.render(
<MainContent />,
document.getElementById('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’}
Numbe {price: PropTypes.objectOf(PropTypes.num
r 4500} ber)
Object
String {name: PropTypes.objectOf(PropType.string
Object ‘TV’} )
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 for restricting the values
by handling various validations.
Syntax:
Product.propTypes = {
Name: PropTypes.string.isRequired
}
Custom Types
- You can create a function or class to configure a
custom type
- You can use the custom type to restrict the value.
Syntax:
Product = {
Name: PropTypes.string
Price: PropTypes.number
}
Products.propTypes = {
TV : Product(Name, Price)
}
What is the Default Type?
- Object
How to define Union of Types?
- A property must allow multiple types but not all
types.
- You define union of types by using
“PropTypes.oneOfType([Type1, Type2])”
Ex:
App.js
Product.propTypes = {
name: PropTypes.string,
price: PropTypes.number,
code: PropTypes.oneOfType([PropTypes.number,
PropTypes.string]),
shippedTo: PropTypes.arrayOf(PropTypes.string)
}
ReactDOM.render(
<MainContent />,
document.getElementById('root')
);
Index.html
<!DOCTYPE html>
<html>
<head>
<title>HTML React App</title>
<link rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/di
st/css/bootstrap.min.css"
integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uI
Kz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2"
crossorigin="anonymous">
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/font-aweso
me/4.7.0/css/font-awesome.min.css"
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-do
m.development.js"></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/prop-type
s/15.7.2/prop-types.js"
integrity="sha512-Ttnt6nUh/1oV+4T/KWkG/ORvlIEOZ
ohMCT/GIzelxTceoIreR2A1r6zmgFnEvi7GgstoDblmpM
O/Gi9CXKTqGQ=="
crossorigin="anonymous"></script>
<script crossorigin
src="https://unpkg.com/@babel/standalone/babel.min
.js"></script>
<script
src="https://code.jquery.com/jquery-3.5.1.slim.min.js"
integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OG
pamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"
crossorigin="anonymous"></script>
<script
src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dis
t/js/bootstrap.bundle.min.js"
integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26Lr
Z/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx"
crossorigin="anonymous"></script>
<script type="text/jsx" src="../src/app.js"></script>
</head>
<body>
<div id="root">
</div>
</body>
</html>
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.getElementById(“container”).style.back
groundColor = “red”;
- React JS also uses “camel case” for configuring the
styles dynamically.
- Dynamic styles are defined by using a style object.
Ex:
App.js
const headingStyle = {
backgroundColor: 'darkcyan',
color: 'white',
textAlign: 'center',
padding: '5px',
marginTop: '10px'
}
const Product = (props) => {
return(
<dl>
<dt style={{backgroundColor: 'gray', color:
'white'}}>Product Code</dt>
<dd>{props.code}</dd>
<dt>Name</dt>
<dd>{props.name}</dd>
<dt>Price</dt>
<dd>{props.price}</dd>
<dt>Shipped To</dt>
<dd>
<ul>
{
props.shippedTo.map((val)=>{
return(
<li key={val}>{val}</li>
)
})
}
</ul>
</dd>
</dl>
)
}
Product.propTypes = {
name: PropTypes.string,
price: PropTypes.number,
code: PropTypes.oneOfType([PropTypes.number,
PropTypes.string]),
shippedTo: PropTypes.arrayOf(PropTypes.string)
}
ReactDOM.render(
<MainContent />,
document.getElementById('root')
);
Embedded Styles
- Embedded styles are defined in “HTML” page by
using <style> element.
- It can embed a set of styles, which are allowed to
reuse across elements.
Index.html
<style>
dt {
background-color: gray;
color:white;
padding:5px;
}
</style>
CSS
- Styles are maintained in a separate CSS file and are
linked to your document.
- You can also import CSS files into component and
use.
- If you are using a modular system for react
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 using a modular system then you
have to link all your CSS files into index.html
<link rel=”stylesheet” href=”../src/app.css”>
Note: You can also use “less and Sass” for CSS.
App.js
function Product(){
function InsertClick(e){
alert(`You Clicked At X Position ${e.clientX}\n Button
Class Name=${e.target.className}`);
}
return (
<div>
<button onClick={InsertClick} name="btnInsert"
className="btn btn-primary">Insert</button>
</div>
)
}
class MainContent extends React.Component
{
render(){
return (
<div className="container-fluid">
<h3>Event Handling</h3>
<Product />
</div>
)
}
}
ReactDOM.render(
<MainContent />,
document.getElementById('root')
);
Events in Class Component
- In Class component events actions are defined as
Methods.
- Event handler points towards specific method.
Ex:
App.js
class Product extends React.Component
{
InsertClick(e){
alert(`X Position: ${e.clientX}\nName :
${e.target.name}`);
}
render(){
return(
<div>
<button name="btnInsert"
onClick={this.InsertClick} className="btn
btn-primary">Insert</button>
</div>
)
}
}
ReactDOM.render(
<MainContent />,
document.getElementById('root')
);
Index.html
<!DOCTYPE html>
<html>
<head>
<title>HTML React App</title>
<link rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/di
st/css/bootstrap.min.css"
integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uI
Kz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2"
crossorigin="anonymous">
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/font-aweso
me/4.7.0/css/font-awesome.min.css"
crossorigin="anonymous" >
<link rel="stylesheet" href="../src/app.css">
<script crossorigin
src="https://unpkg.com/react@17/umd/react.develop
ment.js"></script>
<script crossorigin
src="https://unpkg.com/react-dom@17/umd/react-do
m.development.js"></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/prop-types/
15.7.2/prop-types.js"
integrity="sha512-Ttnt6nUh/1oV+4T/KWkG/ORvlIEOZo
hMCT/GIzelxTceoIreR2A1r6zmgFnEvi7GgstoDblmpMO/
Gi9CXKTqGQ==" crossorigin="anonymous"></script>
<script crossorigin
src="https://unpkg.com/@babel/standalone/babel.min
.js"></script>
<script
src="https://code.jquery.com/jquery-3.5.1.slim.min.js"
integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OG
pamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"
crossorigin="anonymous"></script>
<script
src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dis
t/js/bootstrap.bundle.min.js"
integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26Lr
Z/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx"
crossorigin="anonymous"></script>
<script type="text/jsx" src="../src/app.js"></script>
</head>
<body>
<div id="root">
</div>
</body>
</html>
Event Handler
- Event handler is a function pointer.
- Multiple controls can use the same function to
handle various functionalities.
Ex:
App.js
DataOperations(e){
switch(e.target.value)
{
case "Insert":
alert("Record Inserted");
break;
case "Update":
alert("Record Updated");
break;
case "Delete":
alert("Record Deleted");
break;
}
}
render(){
return(
<div>
<div className="btn-group">
<button name="btnInsert" value="Insert"
onClick={this.DataOperations} className="btn
btn-primary">Insert</button>
<button name="btnUpdate" value="Update"
onClick={this.DataOperations} className="btn
btn-success">Update</button>
<button name="btnDelete" value="Delete"
onClick={this.DataOperations} className="btn
btn-danger">Delete</button>
</div>
<h2 align="center"></h2>
</div>
)
}
}
ReactDOM.render(
<MainContent />,
document.getElementById('root')
);
Note: State defined for a component is initialized into
component memory.
The methods configured with event handler
must bind with the component memory.
Syntax:
{this.buttonClick.bind(this)}
Ex:
App.js
class Product extends React.Component
{
constructor(props){
super(props);
this.state = {
msg: "Select Database Command"
}
this.InsertClick = this.InsertClick.bind(this);
this.UpdateClick = this.UpdateClick.bind(this);
this.DeleteClick = this.DeleteClick.bind(this);
}
InsertClick(){
this.setState(state=>({
msg: state.msg = "Record Inserted"
}));
}
UpdateClick(){
this.setState(state=>({
msg: state.msg = "Record Updated"
}));
}
DeleteClick(){
this.setState(state=>({
msg: state.msg = "Record Deleted Successfully.."
}));
}
render(){
return(
<>
<div className="btn-group">
<button onClick={this.InsertClick} className="btn
btn-primary">Insert</button>
<button onClick={this.UpdateClick}
className="btn btn-success">Update</button>
<button onClick={this.DeleteClick} className="btn
btn-danger">Delete</button>
</div>
<h2 className="text-center">{this.state.msg}</h2>
</>
)
}
}
ReactDOM.render(
<MainContent />,
document.getElementById('root')
);
Index.html
<!DOCTYPE html>
<html>
<head>
<title>HTML React App</title>
<link rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/di
st/css/bootstrap.min.css"
integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uI
Kz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2"
crossorigin="anonymous">
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/font-aweso
me/4.7.0/css/font-awesome.min.css"
crossorigin="anonymous" >
<link rel="stylesheet" href="../src/app.css">
<script crossorigin
src="https://unpkg.com/react@17/umd/react.develop
ment.js"></script>
<script crossorigin
src="https://unpkg.com/react-dom@17/umd/react-do
m.development.js"></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/prop-types/
15.7.2/prop-types.js"
integrity="sha512-Ttnt6nUh/1oV+4T/KWkG/ORvlIEOZo
hMCT/GIzelxTceoIreR2A1r6zmgFnEvi7GgstoDblmpMO/
Gi9CXKTqGQ==" crossorigin="anonymous"></script>
<script crossorigin
src="https://unpkg.com/@babel/standalone/babel.min
.js"></script>
<script
src="https://code.jquery.com/jquery-3.5.1.slim.min.js"
integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OG
pamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"
crossorigin="anonymous"></script>
<script
src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dis
t/js/bootstrap.bundle.min.js"
integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26Lr
Z/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx"
crossorigin="anonymous"></script>
<script type="text/jsx" src="../src/app.js"></script>
</head>
<body>
<div id="root">
</div>
</body>
</html>
ReactDOM.render(
<MainContent />,
document.getElementById('root')
);
InsertClick(){
this.setState({
msg: 'Record Inserted'
})
}
render(){
return(
<>
<div className="btn-group">
<button onClick={this.InsertClick} className="btn
btn-primary">Insert</button>
</div>
<h2 className="text-center">{this.state.msg}</h2>
</>
)
}
}
ReactDOM.render(
<MainContent />,
document.getElementById('root')
);
Ex: DOM Event Handler
App.js
class Product extends React.Component
{
constructor(props){
super(props);
this.state = {
msg : 'Select Database Operation'
}
InsertClick(){
this.setState({
msg: 'Record Inserted'
})
}
render(){
return(
<>
<div className="btn-group">
<button onClick={this.InsertClick.bind(this)}
className="btn btn-primary">Insert</button>
</div>
<h2 className="text-center">{this.state.msg}</h2>
</>
)
}
}
ReactDOM.render(
<MainContent />,
document.getElementById('root')
);
Ex: Without bind() method
class Product extends React.Component
{
constructor(props){
super(props);
this.state = {
msg : 'Select Database Operation'
}
}
InsertClick(){
this.setState({
msg: 'Record Inserted'
})
}
render(){
return(
<>
<div className="btn-group">
<button onClick={()=> this.InsertClick()}
className="btn btn-primary">Insert</button>
</div>
<h2 className="text-center">{this.state.msg}</h2>
</>
)
}
}
class MainContent extends React.Component
{
render(){
return (
<div className="container-fluid">
<h3>Event Handling</h3>
<Product />
</div>
)
}
}
ReactDOM.render(
<MainContent />,
document.getElementById('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} className="btn
btn-primary">Insert</button>
</div>
<h2 className="text-center">{this.state.msg}</h2>
</>
)
}
}
InsertClick(){
document.write("Record Inserted");
}
render(){
return(
<>
<div className="btn-group">
<button onClick={this.InsertClick} className="btn
btn-primary">Insert</button>
</div>
<h2 className="text-center"></h2>
</>
)
}
}
ReactDOM.render(
<MainContent />,
document.getElementById('root')
);
ReactDOM.render(
<MainContent />,
document.getElementById('root')
);
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
key up.
- onKeyPress : Indicates actions to perform
when user finish a key and uses another key.
Properties:
- keyCode
- charCode
- shiftKey
- ctrlKey
- which
- key [Return the key used]
ReactDOM.render(
<MainContent />,
document.getElementById('root')
);
ReactDOM.render(
<MainContent />,
document.getElementById('root')
);
ReactDOM.render(
<MainContent />,
document.getElementById('root')
);
ReactDOM.render(
<MainContent />,
document.getElementById('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.GetColor = this.GetColor.bind(this);
this.SetDefaultColor =
this.SetDefaultColor.bind(this);
}
GetColor(e){
switch(e.target.id){
case "red":
this.setState({
styleObj: {
color: 'red'
}
})
break;
case "green":
this.setState({
styleObj: {
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} className="row
mr-5">
<div className="col" id="red"
className="bg-danger">
Red color
</div>
<div className="col" id="green"
className="bg-success" >
Green color
</div>
<div className="col" id="blue"
className="bg-info">
Blue color
</div>
</div>
<h1 style={this.state.styleObj}>Sample Text</h1>
</>
)
}
}
ReactDOM.render(
<MainContent />,
document.getElementById('root')
);
Ex: Accessing the mouse pointier position on
mousemove
App.js
class MouseDemo extends React.Component
{
constructor(props){
super(props);
this.state = {
styleObj : {
position: '',
left: '',
top: ''
}
}
this.GetMousePosition =
this.GetMousePosition.bind(this);
}
GetMousePosition(e){
this.setState({
styleObj: {
position: 'fixed',
left: e.clientX + 'px',
top: e.clientY + 'px'
}
})
}
render(){
return(
<>
<div onMouseMove={this.GetMousePosition}>
<div style={{height:'1000px'}}>
</div>
<img style={this.state.styleObj} src="flag.gif"
height="50" width="50"/>
</div>
</>
)
}
}
ReactDOM.render(
<MainContent />,
document.getElementById('root')
);
ReactDOM.render(
<MainContent />,
document.getElementById('root')
);
ReactDOM.render(
<MainContent />,
document.getElementById('root')
);
ReactDOM.render(
<MainContent />,
document.getElementById('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
{
SubmitClick(e){
alert(`Name=${e.target[0].value}\nMobile=${e.target[1]
.value}`)
}
render(){
return(
<>
<form onSubmit={this.SubmitClick}>
<dl>
<dt>User Name</dt>
<dd><input type="text" name="username"
/></dd>
<dt>Mobile</dt>
<dd>
<input type="text" name="mobile" />
</dd>
</dl>
<button>Submit</button>
</form>
</>
)
}
}
ReactDOM.render(
<MainContent />,
document.getElementById('root')
);
ReactDOM.render(
<MainContent />,
document.getElementById('root')
);
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
TouchStart(e){
if(e.touches[0].clientX >= 24 &&
e.touches[0].clientX<=203) {
this.setState({
shoeName: 'Nike Casuals'
});
}
if(e.touches[0].clientX >= 230 &&
e.touches[0].clientX<=401) {
this.setState({
shoeName: 'Lee Cooper Boot'
});
}
render(){
return (
<>
<div onTouchStart={this.TouchStart}>
<img src="shoe.jpg" width="200" height="200" />
<img src="shoe1.jpg" width="200" height="200" />
</div>
<h2>You Touched : {this.state.shoeName} </h2>
</>
)
}
}
ReactDOM.render(
<MainContent />,
document.getElementById('root')
);
Ex:
App.js
ReactDOM.render(
<MainContent />,
document.getElementById('root')
);
onTouchStart : It fires up when user starts the
touch.
onTouchMove : It fires up while dragging on
touch.
onTouchEnd : It fires up when touch stopped.
ReactDOM.render(
<MainContent />,
document.getElementById('root')
);
function LoginSuccess(props){
return <h2>Login Success..</h2>
}
function LoginFailure(props){
return <h2>Login Failed..</h2>
}
if(e.target[0].value=='john' &&
e.target[1].value=='admin')
{
this.setState({
content: <LoginSuccess />
})
} else {
this.setState({
content: <LoginFailure />
})
}
}
render(){
return (
<>
<h3>User Login</h3>
<form onSubmit={this.LoginClick} >
<dl>
<dt>User Name</dt>
<dd><input type="text"/></dd>
<dt>Password</dt>
<dd><input type="password"/></dd>
</dl>
<button>Login</button>
</form>
<div>
{this.state.content}
</div>
</>
)
}
}
ReactDOM.render(
<MainContent />,
document.getElementById('root')
);
ReactDOM.render(
<MainContent/>,
document.getElementById('root')
);
Ex: Changing view without defining separate
components.
ReactDOM.render(
<MainContent/>,
document.getElementById('root')
);
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>
<table 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>
</table>
</div>
)
} else {
return(
<div>
<table 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>
</table>
</div>
)
}
}
}
ReactDOM.render(
<MainContent/>,
document.getElementById('root')
);
render(){
if(this.state.viewName=='Basic'){
return(
<div>
<h3>Basic Details</h3>
</div>
)
} else if (this.state.viewName=='Preview'){
return(
<div>
<h3>Product Preview</h3>
</div>
)
} else {
return(
<div>
<h3>Summary</h3>
</div>
)
}
}
}
class MainContent extends React.Component {
render(){
return(
<div className="container-fluid">
<ProductComponent />
</div>
)
}
}
ReactDOM.render(
<MainContent/>,
document.getElementById('root')
);
{
this.state.viewName=='Details'?
<h3>Details</h3>:
this.state.viewName=='Preview'?
<h3>Preview</h3>:
<h3>Summary</h3>
}
Ex:
function BasicInfo(){
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>
<ul>
<li>Feature-1</li>
<li>Feature-2</li>
<li>Feature-3</li>
</ul>
</div>
</div>
</div>
)
}
ReactDOM.render(
<MainContent/>,
document.getElementById('root')
);
Component Lifecycle
- Every component has various 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 of 3 phases
o Mounting
o Updating
o Unmounting
}
Refresh(){
location.reload();
}
render(){
return(
<div>
<button onClick={this.componentWillUnmount}
>Unmount</button>
<button onClick={this.Refresh}>Refresh</button>
<p>{this.state.date.toLocaleTimeString()}</p>
<p>{this.state.msg}</p>
</div>
)
}
}
class MainContent extends React.Component {
render(){
return(
<div className="container-fluid">
<ProductComponent />
</div>
)
}
}
ReactDOM.render(
<MainContent/>,
document.getElementById('root')
);
Ex:
App.js
class SuccessComponent extends React.Component
{
componentWillMount(){
alert("Success component requested..");
}
componentDidMount() {
alert("Success Component Mounted..");
}
componentWillUnmount(){
alert("Success Disposed..");
}
render(){
return(
<h2>Login Success..</h2>
)
}
}
class ErrorComponent extends React.Component
{
componentWillMount(){
alert("Error Component Requested");
}
componentDidMount() {
alert("Error Component Mounted..");
}
componentWillUnmount(){
alert("Error Disposed..");
}
render(){
return(
<h2>Invalid Password</h2>
)
}
}
class ProductComponent extends React.Component
{
constructor(props) {
super(props);
this.state = {
msg: ''
}
this.SuccessClick = this.SuccessClick.bind(this);
this.ErrorClick = this.ErrorClick.bind(this);
}
SuccessClick(){
this.setState({
msg: <SuccessComponent />
})
}
ErrorClick(){
this.setState({
msg: <ErrorComponent />
})
}
render(){
return(
<div>
<button onClick={this.SuccessClick}
>Success</button>
<button onClick={this.ErrorClick}>Error</button>
<div>
<p>
{this.state.msg}
</p>
</div>
</div>
)
}
}
class MainContent extends React.Component {
render(){
return(
<div className="container-fluid">
<ProductComponent />
</div>
)
}
}
ReactDOM.render(
<MainContent/>,
document.getElementById('root')
);
React Application Interacting with API
Distributed Computing Architecture
- Distributed computing allows 2 different
applications running on 2 different machines to
share information. OR 2 different applications
running of 2 different process in the same machine
can share information.
- There are various distributed computing
technologies
o CORBA
o DCOM
o RMI
o EJB
o Web Service [All technologies]
o Remoting etc.
- Web Service Specifications
o SOAP
▪ Request and Response will in XML
o REST
▪ Request will a simple query and Response
will in XML or Optionally JSON.
o JSON
▪ Request and Response will be JSON.
- React requires a “Tool Chain” to configuring
distribute computing architecture and build
distributed computing apps.
- Client-Side Application is created by using
“Create-React-App” [SPA in React]
o A Package Manager [NPM]
o Bundler [Webpack or Parcel]
o A Compiler [Babel]
- The “Tool Chain” used for React Distributed
Application
o Next.js – Framework for static and
server-rendered applications [Node.js, JSP,
.NET, PHP].
o Gatsby – For creating static website with
React. [Improve the load time]
o Nx – tool kit for “Full Stack development”
using React. [React, Next.js, Express,
MongoDB]
o Razzle – Server-Side Rendering Framework
o Ionic, Native Script, Cordova – Framework to
build cross platform mobile app with React.
MongoDB Terminology:
RDBMS MongoDB
Database Database
Table Collection
Records / Rows Documents
Field Field
Joins Embedded Documents
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 = clientObj.db("shoppingdb");
database.collection("tblproducts").find().toArray(functi
on (err, documents){
if(!err) {
res.send(documents);
}
})
}
})
});
app.listen(8080);
console.log("Server Started: http://127.0.0.1:8080");
Product.js
import React from 'react';
import $ from 'jquery';
export default class ProductComponent extends
React.Component {
constructor(props) {
super(props);
this.state = {
ProductId: '',
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({
ProductId: response[0].ProductId,
Name: response[0].Name,
Price: response[0].Price,
InStock: response[0].InStock
})
}
})
}
render(){
return(
<div>
<h2>Get Data from API</h2>
<dl>
<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>
</dl>
</div>
)
}
}
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>
<table 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>
</table>
</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';
ReactDOM.render(
<React.StrictMode>
<ProductComponent />
</React.StrictMode>,
document.getElementById('root')
);
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]
axios({
method: ‘POST’,
url: ‘api_url’,
data: { }
})
Shorthand Requests
axios.get(url)
axios.post(url, data[])
axios.put()
axios.delete()
useState():
- It allows React developers to update, handle and
manipulate state inside functional components
without converting into class component.
Syntax:
function App() {
const [name, setName] = useState(‘John’);
OnButtonClick = () => setName(‘David’);
}
return <div> {name} </div>
Axios in React Application
- Install axios for your project
> npm install axios
- Add a new file into “src”
ProductDetailsComponent.js
axios.get("http://127.0.0.1:8080/getproducts")
.then(res => {
this.setState({
products: res.data
})
})
}
render(){
return(
<div>
<h2>Products List</h2>
<table 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>
</table>
</div>
)
}
}
const data = {
ProductId: this.state.data.ProductId,
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 className="container">
<h2>Add Product</h2>
<form onSubmit={this.SubmitClick}>
<div>
<dl>
<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>
</dl>
<button>Add Product</button>
</div>
</form>
<h2>Products List {this.state.msg} </h2>
<table className="table 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>
</table>
</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 configure a state hook for every element
and access its value.
Ex:
import React from 'react';
Ex:
import React from 'react';
import {useFormik} from 'formik';
const FormLibraryDemo = ( ) => {
const formik = useFormik({
initialValues: {
ProductId: '',
Name: '',
Price: ''
},
onSubmit: values => {
console.log(JSON.stringify(values));
}
})
return(
<div>
<form onSubmit={formik.handleSubmit} >
<dl>
<dt>Product Id</dt>
<dd>
<input type="text" name="ProductId"
value={formik.values.ProductId}
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>
</dl>
<button>Register</button>
</form>
</div>
)
}
export default FormLibraryDemo;
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;
}
Yup Library
- It provides object schema validation.
- It provides a 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 key
refers to validation error and value refers to
validation message.
Syntax:
validationSchema: yup.object({
Name:
yup.DataType().required().max().email()
})
- Yup library uses “formik.getFieldProps()” that can
give access to values of elements.
Syntax:
<input type=”text” name=”Name”
{…formik.getFieldProps(“Name”)} />
Ex:
YupValidationDemo.js
import React from 'react';
import {useFormik} from 'formik';
import * as yup from 'yup';
Formik Components
- Formik library provides pre-defined component
used for designing a form and its validations.
- The built-in components of Formik library
o <Formik />
o <Form />
o <Field />
o <ErrorMessage />
Syntax:
<formik initialValues = {
{ Name: ‘ ‘, Salary: ‘ ‘, Email: ‘ ‘ }
},
validationSchema = {
},
onsubmit = {
}
{ props => (
<Form>
<Field name=”Name” type=”text”>
</Field>
<ErrorMessage name=”Name”>
</ErrorMessage>
</Form>
)
}
Syntax:
<Formik initialValues={} validationSchema={}
onSubmit={}>
{
props=> ()
}
</Formik>
Ex:
ValidationComponent.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 too short")
.max(10, "Name too long"),
Salary: yup.number()
.required("Salary Required"),
Email: yup.string()
.required("Email Required")
.email("Invalid Email")
})
} onSubmit = {values=> {
alert(JSON.stringify(values))
}} >
{
props => (
<div>
<h3>Register User</h3>
<Form>
<dl>
<dt>Name</dt>
<dd>
<Field name="Name"
type="text"></Field>
</dd>
<dd className="text-danger">
<ErrorMessage
name="Name"></ErrorMessage>
</dd>
<dt>Salary</dt>
<dd>
<Field name="Salary"
type="text"></Field>
</dd>
<dd className="text-danger">
<ErrorMessage
name="Salary"></ErrorMessage>
</dd>
<dt>Email</dt>
<dd>
<Field name="Email"
type="text"></Field>
</dd>
<dd className="text-danger">
<ErrorMessage
name="Email"></ErrorMessage>
</dd>
<dt>Your City</dt>
<dd>
<Field name="City" as="select">
<option>Delhi</option>
<option>Hyd</option>
</Field>
</dd>
</dl>
<button
disabled={props.isValid==false}>Register</button>
<button
disabled={props.dirty==false}>Save</button>
</Form>
</div>
)
}
</Formik>
)
}
ReactDOM.render(
<ValidationComponent/>,
document.getElementById("root")
)
export default ValidationComponent;
Styles using Validation Attributes
- You can dynamically apply styles based on
validation properties
Syntax:
<Form
style={props.isValid?{backgroundColor:'green'}:{backgr
oundColor:'red'}}>
Routing Architecture:
Ex:
AppHome.js
import React from 'react';
import { BrowserRouter as Router, Route} from
'react-router-dom';
Ex:
AppHome.js
function Home(){
return(
<div>
<h2>Amazon Home</h2>
<p>Shopping Home Page</p>
</div>
)
}
function Electronics(){
return(
<div>
<h2>Electronics 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="100" />
</div>
)
}
function Fashion(){
return(
<div>
<h2>Fashion Home</h2>
<img src="Images/shirt.jpg" width="100"
height="100" />
<img src="Images/jeans.jpg" width="100"
height="100" />
</div>
)
}
function NotFound(){
return(
<div>
<h2>Not-Found</h2>
<p>Page you requested <code>
{window.location.href} </code> - Not Found</p>
<p><Link to="/home">Back to Home</Link></p>
</div>
)
}
export default class AppHome extends
React.Component
{
render(){
return(
<Router>
<header>
<h1>Amazon Shopping</h1>
</header>
<div>
<ul style={{display:'flex', listStyle:'none'}}>
<li><Link to="/home">Home</Link></li>
<li><Link
to="/electronics">Electronics</Link></li>
<li><Link
to="/footwear">Footwear</Link></li>
<li><Link
to="/fashion">Fashion</Link></li>
</ul>
</div>
<hr />
<Switch>
<Route exact path="/">
<Home />
</Route>
<Route path="/home">
<Redirect to="/" />
</Route>
<Route path="/electronics">
<Electronics />
</Route>
<Route path="/footwear">
<Footwear />
</Route>
<Route path="/fashion">
<Fashion />
</Route>
<Route path="*" >
<NotFound />
</Route>
</Switch>
</Router>
)
}
}
Index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport"
content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link rel="apple-touch-icon"
href="%PUBLIC_URL%/logo192.png" />
<!--
manifest.json provides metadata used when your
web app is installed on a
user's mobile device or desktop. See
https://developers.google.com/web/fundamentals/we
b-app-manifest/
-->
<link rel="manifest"
href="%PUBLIC_URL%/manifest.json" />
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder
during the build.
Only files inside the `public` folder can be
referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico",
"%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a
non-root public URL.
Learn how to configure a non-root public URL by
running `npm run build`.
-->
<title>React App</title>
<link
href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-b
eta2/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6w
uqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl"
crossorigin="anonymous">
<style>
li {
margin-right: 30px;
border:2px solid tomato;
border-radius: 10px;
padding: 5px;
width: 100px;
text-align: center;
}
a{
text-decoration: none;
color:tomato;
font-weight: bold;
}
</style>
</head>
<body class="container">
<noscript>You need to enable JavaScript to run this
app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an
empty page.
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
2val
- 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>Electronics 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="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 Details(){
let {id, name, price} = useParams();
return(
<div>
<h2>Details Page</h2>
<dl>
<dt>Product Id</dt>
<dd>{id}</dd>
<dt>Name</dt>
<dd>{name}</dd>
<dt>Price</dt>
<dd>{price}</dd>
</dl>
</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>
<ul style={{display:'flex', listStyle:'none'}}>
<li><Link to="/home">Home</Link></li>
<li><Link
to="/electronics">Electronics</Link></li>
<li><Link
to="/footwear">Footwear</Link></li>
<li><Link
to="/fashion">Fashion</Link></li>
<li><Link
to="/details/1/mobile/5600">Details</Link></li>
</ul>
</div>
<hr />
<Switch>
<Route exact path="/">
<Home />
</Route>
<Route path="/home">
<Redirect to="/" />
</Route>
<Route path="/electronics">
<Electronics />
</Route>
<Route path="/footwear">
<Footwear />
</Route>
<Route path="/fashion">
<Fashion />
</Route>
<Route path="/details/:id/:name/:price">
<Details/>
</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>Electronics 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="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 = [
{CategoryId: 1, CategoryName: "Electronics"},
{CategoryId: 2, CategoryName: "Footwear"}
];
return(
<div>
<h2>Categories</h2>
<ol>
{
categories.map(cat =>
<li key={cat.CategoryId}><Link
to={'/products/' +
cat.CategoryId}>{cat.CategoryName}</Link></li>
)
}
</ol>
</div>
)
}
let products = [
{ProductId:1, Name: 'Samsung TV', Price: 45000.33,
CategoryId: 1},
{ProductId:2, Name: 'Nike Casuals', Price: 6000.44,
CategoryId: 2},
{ProductId:3, Name: 'Earpods', Price: 3500.44,
CategoryId: 1},
{ProductId:4, Name: 'Lee Boot', Price: 6300.33,
CategoryId: 2}
];
function Products(){
let {id} = useParams();
function Details(){
let {id} = useParams();
let searchedProduct =
products.find(x=>x.ProductId==id);
return(
<div>
<h2>Details Page</h2>
<dl>
<dt>Name</dt>
<dd>{searchedProduct.Name}</dd>
<dt>Price</dt>
<dd>{searchedProduct.Price}</dd>
<dt>ProductId</dt>
<dd>{searchedProduct.ProductId}</dd>
</dl>
</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>
<ul style={{display:'flex', listStyle:'none'}}>
<li><Link to="/home">Home</Link></li>
<li><Link
to="/electronics">Electronics</Link></li>
<li><Link
to="/footwear">Footwear</Link></li>
<li><Link
to="/fashion">Fashion</Link></li>
<li><Link
to="/categories">Categories</Link></li>
<li><Link
to="/details/1/mobile/5600">Details</Link></li>
</ul>
</div>
<hr />
<Switch>
<Route exact path="/">
<Home />
</Route>
<Route path="/home">
<Redirect to="/" />
</Route>
<Route path="/electronics">
<Electronics />
</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">
<Details/>
</Route>
<Route path="*" >
<NotFound />
</Route>
</Switch>
</Router>
)
}
}
Authentication / Secured Routes
- Application-level security includes
o XSS [Cross Site Scripting Attack]
o Request Forgery
o Authorization / Authentication
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 for unsecured and HTTPS for secured
- 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={Hello}>Test</button>
// Secured
<a href={`javascript:${Hello}`}>Click
Here..</a> //Not Secured
</div>
)
}
- If you want HTML to use the string with script then
you have to use “DOM Sanitizer”
- It allows to use the functions safely in DOM HTML
elements.
- It requires “dangerouslySetInnerHTML” 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={Hello}>Test</button>
<a
href={purify.sanitize(`javascript:${Hello()}`)}>Click
Here..</a>
</div>
)
}
Syntax:
const msg = “<b>Hello</b>”;
<div
dangerouslySetInnerHTML={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>Hello</b>";
return(
<div>
<h2>Security Test</h2>
<div
dangerouslySetInnerHTML={{__html:purify.sanitize(
msg)}} ></div>
</div>
)
}
Cookies in React
- Cookie is a 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 set expiry for cookie.
Ex:
- Import “useState”
import React, {useState} from 'react';
- Create a component
function Login(){
const [message, setMessage] = useState('');
const CreateCookie = (email) => {
localStorage.setItem('email', email);
setMessage("Cookie Created");
}
return(
<div>
<label>Email :</label>
<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(['useremail']);
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>Public Page</h2>
)
}
function ProtectedPage(){
return(
<h2>Protected Page</h2>
)
}
function useAuth() {
return useContext(authContext);
}
function LoginPage(){
let auth = useAuth();
let history = useHistory();
let location = useLocation();
let {from} = location.state || {from: {pathname: "/"}};
let login = () => {
auth.signin(()=> {
history.replace(from);
})
}
return(
<div>
<p>Please Login to View Protected Page</p>
<button onClick={login}>Login</button>
</div>
)
}
function AuthButton(){
let history = useHistory();
let auth = useAuth();
return auth.user ? (<p>Welcome 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();
})
}
const signout = callback => {
return fakeAuth.signout(()=> {
setUser(null);
callback();
})
}
return {
user,
signin,
signout
}
}
const fakeAuth = {
isAuthenticated : false,
signin(callback) {
fakeAuth.isAuthenticated = true;
setTimeout(callback, 100);
},
signout(callback) {
fakeAuth.isAuthenticated = false;
setTimeout(callback, 100);
}
}
function ProvideAuth({children}) {
const auth = useProvideAuth();
return (
<authContext.Provider value={auth}>
{children}
</authContext.Provider>
)
}
/* Theme variables */
import './theme/variables.css';
return (
<Card className={classes.root}>
<CardHeader
avatar={
<Avatar aria-label="recipe"
className={classes.avatar}>
R
</Avatar>
}
action={
<IconButton aria-label="settings">
<MoreVertIcon />
</IconButton>
}
title="Shrimp and Chorizo Paella"
subheader="September 14, 2016"
/>
<CardMedia
className={classes.media}
image="/static/images/cards/paella.jpg"
title="Paella dish"
/>
<CardContent>
<Typography variant="body2"
color="textSecondary" component="p">
This impressive paella is a 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 disableSpacing>
<IconButton aria-label="add to favorites">
<FavoriteIcon />
</IconButton>
<IconButton aria-label="share">
<ShareIcon />
</IconButton>
<IconButton
className={clsx(classes.expand, {
[classes.expandOpen]: expanded,
})}
onClick={handleExpandClick}
aria-expanded={expanded}
aria-label="show more"
>
<ExpandMoreIcon />
</IconButton>
</CardActions>
<Collapse in={expanded} timeout="auto"
unmountOnExit>
<CardContent>
<Typography paragraph>Method:</Typography>
<Typography paragraph>
Heat 1/2 cup of the broth in a pot until
simmering, add saffron and set aside for 10
minutes.
</Typography>
<Typography paragraph>
Heat oil in a (14- to 16-inch) paella pan or a
large, deep skillet over medium-high
heat. Add chicken, shrimp and chorizo, and cook,
stirring occasionally until lightly
browned, 6 to 8 minutes. Transfer shrimp to a
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 remaining 4 1/2 cups chicken
broth; bring to a boil.
</Typography>
<Typography paragraph>
Add rice and stir very gently to distribute. Top
with artichokes and peppers, and cook
without stirring, until most of the 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 to 7
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
return (
<div className={classes.root}>
<Avatar alt="Remy Sharp"
src="/static/images/avatar/1.jpg" />
<Avatar alt="Travis Howard"
src="/static/images/avatar/2.jpg" />
<Avatar alt="Cindy Baker"
src="/static/images/avatar/3.jpg" />
</div>
);
}
Ex: Dialog
import React from 'react';
import Button from '@material-ui/core/Button';
import Dialog from '@material-ui/core/Dialog';
import DialogActions from
'@material-ui/core/DialogActions';
import DialogContent from
'@material-ui/core/DialogContent';
import DialogContentText from
'@material-ui/core/DialogContentText';
import DialogTitle from
'@material-ui/core/DialogTitle';
return (
<div>
<Button variant="outlined" color="primary"
onClick={handleClickOpen}>
Open alert dialog
</Button>
<Dialog
open={open}
onClose={handleClose}
aria-labelledby="alert-dialog-title"
aria-describedby="alert-dialog-description"
>
<DialogTitle id="alert-dialog-title">{"Use Google's
location service?"}</DialogTitle>
<DialogContent>
<DialogContentText id="alert-dialog-description">
Let Google help apps determine location. This
means sending anonymous location data to
Google, even when no apps are running.
</DialogContentText>
</DialogContent>
<DialogActions>
<Button onClick={handleClose} color="primary">
Disagree
</Button>
<Button onClick={handleClose} color="primary"
autoFocus>
Agree
</Button>
</DialogActions>
</Dialog>
</div>
);
}