Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
9 views

React Library (2)

This document provides a comprehensive guide on integrating React into existing applications and creating new React applications. It covers installation steps, component creation, data binding, and the use of libraries like Babel and Bootstrap. Additionally, it explains key concepts of JavaScript and Object-Oriented Programming relevant to React development.

Uploaded by

Venkata Lokendra
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

React Library (2)

This document provides a comprehensive guide on integrating React into existing applications and creating new React applications. It covers installation steps, component creation, data binding, and the use of libraries like Babel and Bootstrap. Additionally, it explains key concepts of JavaScript and Object-Oriented Programming relevant to React development.

Uploaded by

Venkata Lokendra
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 90

Use React in Existing Application with Offline Library

------------------------------------------------------------------------

- Download and Install React and Babel library for your project

>npm install react --save


>npm install react-dom --save
>npm install @babel/standalone --save

- All library files are copied into "node_modules"

- Link the files to your HTML page

react.developement.js
react-dom.development.js
babel.js

Ex: Home.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Home</title>
<script src="../node_modules/react/umd/react.development.js"></script>
<script src="../node_modules/react-dom/umd/react-dom.development.js"></script>
<script src="../node_modules/@babel/standalone/babel.js"></script>
<script type="text/babel">
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render("Welcome to React Home");
</script>
</head>
<body>
<div id="root"></div>
</body>
</html>

Note: "render()" of virtual DOM can render plain text content [RC Data Type]
or a component.

Component can be a class or a function that renders Layout.

Component Rule
- It can be a function or class
- It must return markup

Syntax:
function Login()
{
return ( <markup> </markup> )
}

- You can render any component into Virtual DOM

root.render(<Login />);

Ex: Home.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Home</title>
<script src="../node_modules/react/umd/react.development.js"></script>
<script src="../node_modules/react-dom/umd/react-dom.development.js"></script>
<script src="../node_modules/@babel/standalone/babel.js"></script>
<script type="text/babel">
function Login(){
return (
<div>
<h2>User Login</h2>
<dl>
<dt>User Name</dt>
<dd><input type="text" /></dd>
<dt>Password</dt>
<dd><input type="password"/></dd>
</dl>
<button>Login</button>
</div>
)
}
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<Login/>);
</script>
</head>
<body>
<div id="root"></div>
</body>
</html>

Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Home</title>
<script src="../node_modules/react/umd/react.development.js"></script>
<script src="../node_modules/react-dom/umd/react-dom.development.js"></script>
<script src="../node_modules/@babel/standalone/babel.js"></script>
<script type="text/babel">
const Login = () => (
<div>
<h2>User Login</h2>
<dl>
<dt>User Name</dt>
<dd><input type="text" /></dd>
<dt>Password</dt>
<dd><input type="password"/></dd>
</dl>
<button>Login</button>
</div>
)
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<Login></Login>);
</script>
</head>
<body>
<div id="root"></div>
</body>
</html>

Create a new React Application

1. Open any location on your PC in command prompt

E:\>npx create-react-app shopping-react


2. Open your project folder in VS code.

3. Application File System comprises of following files and folder

File / Folder Description


--------------------------------------------------------------------------
node_modules It comprises all library files.
public It comprises of static resources [html, images, text..]
src It comprises of dynamic resources [js, ts, css, scss..]
.gitignore It configures the resources, which are intended not
to include into GIT.
package.json It comprises of project meta data.
package-lock.json It is used by installer to install the packages locally.
readme.md It is help document

- Open Terminal

>npm start

http://localhost:3000
Class
Class Members
- Property
- Accessor
- Method
- Constructor
Inheritance

Inheritance Rule:
- The derived class constructor must be called a super class constructor.
- Newly extended class is called a derived class.
- Existing class is called super.

class Super
{
constructor() { }
}
class Derived extends Super
{
constructor() {
super();
}
}
let obj = new Derived();
Ex:
<script>
class Super
{
constructor(){
document.write("Super Class Constructor<br>");
}
}
class Derived extends Super
{
constructor(){
super();
document.write("Derived Class Constructor");
}
}
let obj = new Derived();
</script>

Polymorphism
- Poly means many
- Morphos means Forms
- Configuring a component to work in different situations and with different behaviors is referred to
as Polymorphism.

Ex:
<script>
class Employee
{
FirstName;
LastName;
Designation;
Print(){
document.write(`${this.FirstName} ${this.LastName} - ${this.Designation}<br>`);
}
}
class Developer extends Employee
{
FirstName = "Raj";
LastName = "Kumar";
Designation = "Developer";
Role = "Developer Role : Build, Debug, Test, Deploy";
Print(){
super.Print();
document.write(this.Role);
}
}
class Admin extends Employee
{
FirstName = "Kiran";
LastName = "Kumar";
Designation = "Admin";
Role = "Admin Role : Authorization, Authentication";
Print(){
super.Print();
document.write(this.Role);
}
}
class Manager extends Employee
{
FirstName = "Tom";
LastName = "Hanks";
Designation = "Manager";
Role = "Manager Role : Approvals";
Print(){
super.Print();
document.write(this.Role);
}
}
let employees = new Array(new Developer(),new Admin(), new Manager());
var designation = prompt("Enter Designation");
for(var employee of employees)
{
if(employee.Designation==designation) {
employee.Print();
}
}
</script>

Summary
- JavaScript Language Basics
Variables
Data Types
Operators
Statements
Functions
- JavaScript OOP
- Modules
- Class
- Properties
- Methods
- Constructor
- Accessors
- Inheritance
- Polymorphism

React
- JavaScript library for building UI.
- React or React JS
- React is used in building UI for SPA. [Single Page Application]
- React is used in PWA [Progressive Web Application] - Mobile
- PWA are built by using React and React Native [iOS, Android].

Features of React
- Virtual DOM
- Modular
- Component Based
- AOT [JIT]

Using React in Existing Web Application


--------------------------------------------------------
1. You can implement react in any page by using "CDN" links
2. You can implement React in any project by downloading the library.
3. React in any page requires following libraries

a) React Core Library


b) React DOM Library
c) Babel Library

- React Core library enables react on page.


- The React DOM library handles Virtual DOM.
- Babel library is a compiler for JavaScript in react.

Ex: CDN Links

https://reactjs.org/docs/cdn-links.html => react , react-dom


https://babeljs.io/docs/en/babel-standalone => babel

<head>
<script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script&gt;
<script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></
script&gt;
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script&gt;
</head>

index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script&gt;
<script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></
script&gt;
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script&gt;
<script type="text/babel">
const root = ReactDOM.createRoot(document.getElementById("container"));
root.render("Hello ! from React");
</script>
</head>
<body>
<h1>React-Web-Application Home</h1>
<div id="container"></div>
</body>
</html>

React upto 17

<script type="text/babel">

ReactDOM.render("Welcome to React", document.getElementById("container"));

</script>

React 18+

<script type="text/babel">
const root = ReactDOM.createRoot(document.getElementById("container"));
root.render("Hello ! from React");
</script>
>npx create-react-app shopping-react

>npm start

1. Client makes a request from browser

http://localhost:3000
2. The request is processed on "Web Server - HttpServer"

3. Request is processed by "HttpHandler" in the HttpProcessing Pipeline.

4. HttpHandler uses a Routing Engine

5. Routing Engine verifies the request by using "Route Table".

6. Route Table comprises information about the resources provided by application.

7. If requested is not available in the route table then it returns 404 : Not Found.

8. If requested path is available then it returns 200: OK

9. AppComponent is rendered into Root of Index.html

10. Index.html is rendered into Browser.

FAQ: Which component is rendered by default?


Ans : "AppComponent"

FAQ: Where is the source for AppComponent?


Ans : It is in "src/app.js"

FAQ: How index.html is able to access the scripts without linking the script files?
Ans: By using "WebPack".

FAQ: What is WebPack?


Ans: WebPack is a bundler, It is used to bundle all resources of your application.
[scripts, styles, images etc..]
It can configure which script to render in the HTML page.
Without linking the script file it can render the scripts.
It uses "Mapping" and "Model Binding".

FAQ: What is the source for Index.html? From where index.html is accessing scripts?
Ans : src/index.js

index.html
<div id="root"> </div>

index.js

const root = document.createRoot(document.getElementById("root"));


root.render(<App/>);

FAQ: Can we run react applications in browsers where JavaScript is disabled?


Ans: No.
FAQ: How to know if javascript is enabled or not?
Ans : <noscript>

React Components
- Component is a template that comprises of
a) Presentation
b) Styles
c) Logic
- Presentation is defined using HTML
- Styles are defined by using CSS
- Logic is defined by JavaScript or TypeScript.
- Components are the building block for React Application.
- React components are designed by using
a) Function
b) Class

- Function
* Light weight
* Less memory
* Fast in rendering
* Hard to extend

- Class
* Heavy
* More memory
* Slow in rendering
* Easy to extend

Function Component
- Component function can be parameter less or parameterized.
- Every function component must return a presentation.

Syntax:
function ComponentName(params)
{
return (<markup> </markup>);
}

- Component uses JSX [JavaScript Extension Library]


- JSX will not allow multiple lines without a block.

<h2>Head-1</h2> //invalid
<p> Line-1 </p>

<div>
<h2></h2>
<p></p>
</div>
- Complete presentation must return as one fragment.

<div> </div>
<> </>
<React.Fragment> </React.Fragment>

- JSX will not allow void elements. Every element must have an end tag.

<img> // invalid
<img> </img>
<img />

- You can't bind any content to an attribute, only properties are allowed.

<div class="form"> // invalid


<div className="form"> // valid
<img src="path"> // valid

reactflow.png
Designing a Component with Bootstrap Styles

1. Install bootstrap and bootstrap-icons library for project

>npm install bootstrap --save


>npm install bootstrap-icons --save

2. Link bootstrap css and icons css to index.js

import '../node_modules/bootstrap/dist/css/bootstrap.css';
import '../node_modules/bootstrap-icons/font/bootstrap-icons.css';

3. Add a new folder into "src" by name "components"

4. Add a subfolder into components "login"

5. Add following files into login

login.component.css

form {
width: 300px;
border:2px solid gray;
padding: 20px;
border-radius: 20px;
}
#form-container {
display: flex;
justify-content: center;
align-items: center;
height: 500px;
}

login.component.js

import './login.component.css';
export function LoginComponent()
{
return(
<div id="form-container" className="container-fluid">
<form>
<h2> <span className="bi bi-person-fill"></span> User Login</h2>
<div className="mb-2">
<label className="form-label">User Name</label>
<div>
<input type="text" className="form-control" />
</div>
</div>
<div className="mb-2">
<label className="form-label">Password</label>
<div>
<input type="password" className="form-control" />
</div>
</div>
<div className="mb-2">
<button className="btn btn-primary w-100">Login</button>
</div>
</form>
</div>
)
}

6. Go to "index.js" in src

import {LoginComponent} from './components/login/login.component';

root.render(
<React.StrictMode>
<LoginComponent />
</React.StrictMode>
);
netflix.zip
Compressed Archive
Data Binding in React
- Data binding is the process of accessing data from source and binding to UI.
- Identifying the changes in UI and updating back to source.
- Data Binding is handled in JavaScript and jQuery by using
a) DOM Methods
b) DOM Events
- React simplifies the data binding.
- Data binding is of 2 types
a) One Way Binding
b) Two Way Binding

- React supports only "One Way Binding".


- One Way Binding is the process of accessing from source and binding to UI.
It is unidirectional.
- React uses data binding expression "{ }"
- React can bind any data without using DOM methods.

Syntax:
var username = "John";

<div> Hello ! {username} </div>

Ex:
data-binding.component.js

export function DataBindingComponent()


{
var product = {
Name: "Samsung TV",
Price: 44500.44,
Stock: true
}
return(
<div className="container-fluid">
<h2>Product Details</h2>
<dl>
<dt>Name</dt>
<dd>{product.Name}</dd>
<dd><input type="text" value={product.Name}/></dd>
<dt>Price</dt>
<dd>{product.Price}</dd>
<dt>Stock</dt>
<dd>{(product.Stock==true)?"Available":"Out of Stock"}</dd>
</dl>
</div>
)
}

collection.map(function(item){

})

Note: Every iterating item which is generated dynamically must have a unique key in React.

Syntax:
collection.map(item=> <li key={item}> { item } </li>)

Ex: Array Type

data-binding.component.js

export function DataBindingComponent()


{
var categories = ["All", "Electronics", "Footwear", "Fashion"];
return(
<div className="container-fluid">
<h2>Arrays</h2>
<ol>
{
categories.map(category=>
<li key={category}>{category}</li>
)
}
</ol>
<select>
{
categories.map(category=>
<option key={category}>{category}</option>
)
}
</select>
<ul className="list-unstyled">
{
categories.map(category=>
<li key={category}><input type="checkbox"/> {category}</li>
)
}
</ul>
<div>
{
categories.map(category=>
<div key={category}>
<button className="w-25">{category}</button>
</div>
)
}
</div>
</div>
)
}

Ex: Array of Objects

data-binding.component.js

export function DataBindingComponent()


{
var products = [
{Name: "TV", Price: 45000.44, Stock: true},
{Name: "Mobile", Price: 34000.33, Stock: false},
{Name: "Nike Casuals", Price:5200.44, Stock:true}
];
return(
<div className="container-fluid">
<h2>Products Table</h2>
<table className="table table-hover">
<thead>
<tr>
<th>Name</th>
<th>Price</th>
<th>Stock</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{
products.map(product=>
<tr key={product.Name}>
<td>{product.Name}</td>
<td>{product.Price}</td>
<td>{(product.Stock==true)?"Available":"Out of Stock"}</td>
<td>
<button className="btn btn-info"><span className="bi
bi-eye-fill"></span></button>
<button className="btn btn-warning ms-2"><span className="bi
bi-pen"></span></button>
<button className="btn btn-danger ms-2"><span className="bi
bi-trash"></span></button>
</td>
</tr>
)
}
</tbody>
</table>
</div>
)
}

Ex: Nested Data

data-binding.component.js

export function DataBindingComponent()


{
var menu = [
{Category: "Electronics", Products: ["TV", "Mobile"]},
{Category: "Footwear", Products: ["Nike Casuals", "Lee Boot"]}
];

return(
<div className="container-fluid">
<h2>Select Category</h2>
{
menu.map(item=>
<details key={item.Category}>
<summary>{item.Category}</summary>
<ul>
{
item.Products.map(product=>
<li key={product}>{product}</li>
)
}
</ul>
</details>
)
}
<h2>Shopping Menu</h2>
<ol>
{
menu.map(item=>
<li key={item.Category}>
{item.Category}
<ul>
{
item.Products.map(product=>
<li key={product}>{product}</li>
)
}
</ul>
</li>
)
}
</ol>
<h2>Select Product</h2>
<select>
{
menu.map(item=>
<optgroup label={item.Category} key={item.Category}>
{
item.Products.map(product=>
<option key={product}>{product}</option>
)
}
</optgroup>
)
}
</select>
</div>
)
}

Ex: Bootstrap Cards

data-binding.component.js

export function DataBindingComponent()


{
var courses = [
{Title: "ASP.NET", Poster: "asp.jpg", Topics:["Web", "API","MVC"]},
{Title: "AWS", Poster: "aws.jpg", Topics:["Cloud","Services","Database"]},
{Title: "Digital Marketing", Poster: "dm.jpg", Topics:["Cloud","Services","Database"]},
{Title: "Data Science", Poster: "ds.jpg", Topics:["Cloud","Services","Database"]}
]

return(
<div className="container-fluid">
<h2>Courses</h2>
<div className="d-flex flex-wrap">
{
courses.map(course=>
<div className="card m-2 p-2">
<img src={course.Poster} className="card-img-top" height="150" />
<div className="card-header">
<h3>{course.Title}</h3>
</div>
<div className="card-body">
<ul>
{
course.Topics.map(topic=>
<li>{topic}</li>
)
}
</ul>
</div>
<div className="card-footer">
<button className="btn btn-primary w-100">Join Course</button>
</div>
</div>
)
}
</div>
</div>
)
}

- Variables are Immutable, so don't use variables for storing data in React.
- Always recommended to use "State".

What is State?
Why we need State?

- Every web application uses protocol "http | https".


- Http is a state less protocol.
- Http uses the mechanism
"Go-Get-Forget"

Go - Establish connection with server


GET - Get Response from server
Forget - Clean up response details

- State less nature is good for server as it manages memory well.


- State less nature is a drawback for client if he need continous operations.
- Web application use various state management techniques
a) Query String
b) Cookie
c) Session
d) Application etc..
- React implicitly provides state to manage data.
- React version upto 17 state is available only for class components.
- React 18+ versions provide state for function components.
- React 18 uses "useState()" hook [method] for function components.

Note: It is always recommended to maintain your data in react state.

- State in function component is defined by using a hook "useState"


- useState is Generic type.
- It is open for any type and also restricts specific data type based on the value type initialized.

Syntax:
import {useState} from 'react';

- useState hook requires a getter and setter


- getter can access value stored in state.
- setter can set value into state.

Syntax:
const {getter, setter} = useState(initialValue);

- State in react can handle any type


a) Primitive
b) Non Primitive

Note: Any react 18 hook can't be used in class components.

FAQ: Why state is configured with const?


Ans : You can't use state without initialization.
State must be ready before you start using component.
"Component is initialized with state"
Syntax:

import { useState } from "react";

export function DataBindingComponent()


{
const [userName, setUserName] = useState("John")
return(
<div className="container-fluid">
<h2>One Way</h2>
User Name : <input type="text" value={userName} />
<p>
Hello ! {userName}
</p>
</div>
)
}

Ex:
import { useState } from "react";

export function DataBindingComponent()


{
const [categories] = useState(["Electronics", "Footwear"]) ;
return(
<div className="container-fluid">
<ol>
{
categories.map(category=>
<li key={category}>{category}</li>
)
}
</ol>
</div>
)
}

Two Way Binding


- React doesn't support 2 way binding.
- You have to implement explicitly.
- Two way binding require Events in React.

Ex:
import { useState } from "react";
export function DataBindingComponent()
{
const [userName, setUserName] = useState("david");

function HandleUserName(e){
setUserName(e.target.value);
}

return(
<div className="container-fluid">
<h2>Register User</h2>
<dl>
<dt>User Name</dt>
<dd><input type="text" onKeyUp={HandleUserName} /></dd>
</dl>
<p>Hello ! {userName}</p>
</div>
)
}

Ex:
import { useState } from "react";

export function DataBindingComponent()


{
const [Name, setName] = useState("");
const [Price, setPrice] = useState(0);
const [City, setCity] = useState("");
const [Stock, setStock] = useState(false);

function NameChange(e){
setName(e.target.value);
}
function PriceChange(e){
setPrice(e.target.value);
}
function CityChange(e){
setCity(e.target.value);
}
function StockChange(e){
setStock(e.target.checked);
}

return(
<div className="container-fluid">
<div className="row">
<div className="col-3">
<h2>Register</h2>
<dl>
<dt>Name</dt>
<dd><input onChange={NameChange} type="text"/></dd>
<dt>Price</dt>
<dd><input onChange={PriceChange} type="number"/></dd>
<dt>City</dt>
<dd>
<select onChange={CityChange}>
<option>Delhi</option>
<option>Hyd</option>
</select>
</dd>
<dt>Stock</dt>
<dd className="form-switch">
<input onChange={StockChange} type="checkbox" className="form-check-input" />
Available
</dd>
</dl>
</div>
<div className="col-9">
<h2>Details</h2>
<dl>
<dt>Name</dt>
<dd>{Name}</dd>
<dt>Price</dt>
<dd>{Price}</dd>
<dt>City</dt>
<dd>{City}</dd>
<dt>Stock</dt>
<dd>{(Stock==true)?"Avaialble":"Out of Stock"}</dd>
</dl>
</div>
</div>
</div>
)
}

Data From API

- API is "Application Programming Interface".


- It is a concept of Distributed Computing.
- Distributed computing allows 2 different applications running on 2 different mechines to share
information.
(or)
2 different application running in 2 different process of same mechine can share
information.

- API main role is to make data reachable to any device and any platform.
- Worlds First API is "Ebay".
- API have 3 specifications
a) SOAP
b) REST
c) JSON
- SOAP [Service Oriented Architecture Protocol]
Consumer => XML request
Provider => XML response
- REST [Representational State Transfer]
Consumer => query request
Provider => XML response
- JSON [JavaScript Object Notation]
Consumer => JSON Request
Provider => JSON Response
- Various Distributed Computing Technologies
CORBA
DCOM
RMI
EJB
Web Services
Remoting

Consuming API in React:


----------------------------------
- React can use various JavaScript promises and jQuery library or any 3rd party for consuming API.
- React implicitly don't have any library for API.

JavaScript Promise fetch()


jQuery Ajax $.getJSON(), $.ajax()
3rd Party axios()
- Axios
- WhatWgFetch

- Storing of API data is done by using "state" : useState()


- You can fetch data from any API and store in a reference of state on various events.
- If you want to fetch the data from API at the time of initialization of component then you have to
use a hook called "useEffect()".

- useEffect is a hook that defines action to perform at the time of


a) Mounting a Component and
b) Unmounting a Component
Syntax:
useEffect(()=>{

},[dependencies]);

Ex: Consuming and Presenting API data using JavaScript Fetch promise

fetch("url").then(response in binary).then(response in JSON).catch()


[XmlHttpRequest]

Nasa.component.js

import { useEffect, useState } from "react";

export function NasaComponent()


{
const [mars, setMars] = useState([]);

function LoadPhotos(){
fetch("https://api.nasa.gov/mars-photos/api/v1/rovers/curiosity/photos?
sol=1000&api_key=DEMO_KEY&quot;)
.then(function(response){
return response.json();
})
.then(function(data){
setMars(data.photos);
})
}

useEffect(()=>{
LoadPhotos();
},[]);

return(
<div className="container-fluid mt-3">
<h2>Mars Rover Photos </h2>
<table className="table table-hover">
<thead>
<tr>
<th>Photo Id</th>
<th>Preview</th>
<th>Camera</th>
<th>Rover</th>
</tr>
</thead>
<tbody>
{
mars.map(item=>
<tr key={item.id}>
<td>{item.id}</td>
<td>
<img src={item.img_src} width="100" height="100" />
</td>
<td>{item.camera.full_name}</td>
<td>{item.rover.name}</td>
</tr>
)
}
</tbody>
</table>
</div>
)
}

Ex: Card Style

import { useEffect, useState } from "react";


import "./nasa.component.css";

export function NasaComponent()


{
const [mars, setMars] = useState([]);

function LoadPhotos(){
fetch("https://api.nasa.gov/mars-photos/api/v1/rovers/curiosity/photos?
sol=1000&api_key=DEMO_KEY&quot;)
.then(function(response){
return response.json();
})
.then(function(data){
setMars(data.photos);
})
}

useEffect(()=>{
LoadPhotos();
},[]);
return(
<div className="container-fluid mt-3">
<h2>Mars Rover Photos </h2>
<div className="d-flex flex-wrap">
{
mars.map(item=>
<div className="card m-2 p-2" id="card">
<img src={item.img_src} className="card-img-top" height="200"/>
<div className="card-body">
<dl>
<dt>Camera</dt>
<dd>{item.camera.full_name}</dd>
<dt>Rover</dt>
<dd>{item.rover.name}</dd>
</dl>
</div>
</div>

)
}
</div>
</div>
)
}

Issues with Fetch


- It is a JavaScript promise which returns data in binary.
- You have to explicitly convert into JSON.
- It uses sync technique. [Blocking]
- Not good in error handling (catch)
- CORS issues. [Cross Origin Resource Sharing]
- Security issues [XSS - Cross Site Scripting Attacks]

jQuery Ajax in React


- jQuery Ajax methods
$.getJSON()
$.ajax()
$.ajaxStart()
$.ajaxStop()
$.ajaxComplete()
$.ajaxSuccess()
$.ajaxError()

- Features
* Reutrns data in JSON
* It can handle any type of data
* No conversions required
* Better in error handling
* Async technique but explicitly
* Handles CORS
* Handle Security issues XSS

Syntax:
$.ajax({
method: "get/post/put/delete",
url: " ",
data: " ",
success: function() { },
error:function() { }
})

- Success function of jQuery returns a response object that contains various response details like
status 404, 200
statusText Not found, OK
data data in file or url
header etc.. request details [method name, host ..]

Ex:
1. Install jQuery
> npm install jquery --save

2. Import jQuery library

import $ from "jquery";

$.ajax({})

nasa.component.js

import { useEffect, useState } from "react";


import "./nasa.component.css";
import $ from 'jquery';

export function NasaComponent()


{
const [mars, setMars] = useState([]);

function LoadPhotos(){
$.ajax({
method: "get",
url: "https://api.nasa.gov/mars-photos/api/v1/rovers/curiosity/photos?
sol=1000&api_key=DEMO_KEY&quot;,
success: (response)=>{
setMars(response.photos);
}
})
}

useEffect(()=>{
LoadPhotos();
},[]);

return(
<div className="container-fluid mt-3">
<h2>Mars Rover Photos </h2>
<div className="d-flex flex-wrap">
{
mars.map(item=>
<div key={item.id} className="card m-2 p-2" id="card">
<img src={item.img_src} className="card-img-top" height="200"/>
<div className="card-body">
<dl>
<dt>Camera</dt>
<dd>{item.camera.full_name}</dd>
<dt>Rover</dt>
<dd>{item.rover.name}</dd>
</dl>
</div>
</div>

)
}
</div>
</div>
)
}

3rd Party
- Axios
- Light weight
- Supports both sync and async techniques
- Can handle multiple requests simultaneously at the same time.

axios({
method:"",
url:" ",
data:" "
})
axios({
[
{ method:"", url:"" }, 0
{ method:"", url:"" } 1
]
})

- Good in error handling


- More secured

Ex:
1. Install axios

> npm install axios --save

2. Import axios

import axios from "axios";

nasa.component.js

import { useEffect, useState } from "react";


import "./nasa.component.css";
import axios from "axios";

export function NasaComponent()


{
const [mars, setMars] = useState([]);

function LoadPhotos(){
axios.get("https://api.nasa.gov/mars-photos/api/v1/rovers/curiosity/photos?
sol=1000&api_key=DEMO_KEY&quot;)
.then(response=> {
setMars(response.data.photos);
})
.catch(ex=>{
console.log(ex);
})
}

useEffect(()=>{
LoadPhotos();
},[]);
return(
<div className="container-fluid mt-3">
<h2>Mars Rover Photos </h2>
<div className="d-flex flex-wrap">
{
mars.map(item=>
<div key={item.id} className="card m-2 p-2" id="card">
<img src={item.img_src} className="card-img-top" height="200"/>
<div className="card-body">
<dl>
<dt>Camera</dt>
<dd>{item.camera.full_name}</dd>
<dt>Rover</dt>
<dd>{item.rover.name}</dd>
</dl>
</div>
</div>

)
}
</div>
</div>
)
}

Shopping ERP with Fakestore API

http://fakestoreapi.com

GET /products [] 20 products { }


GET /products/1 {} specific product
GET /products/categories [] categories
GET /products/category/electronics [] products of specific category

shopping.component.js

import { useEffect, useState } from "react";


import axios from "axios";
import "./shopping.component.css";

export function ShoppingComponent()


{
const [categories, setCategories] = useState([]);
const [products, setProducts] = useState([]);
const [category, setCategory] = useState("all");
function LoadCategories(){
axios.get("http://fakestoreapi.com/products/categories&quot;)
.then(response=>{
response.data.unshift("all");
setCategories(response.data);
})
}

function LoadProducts(url){
axios.get(url).then(response=> {
setProducts(response.data);
});
}

useEffect(()=>{
LoadCategories();
LoadProducts("http://fakestoreapi.com/products&quot;);
},[]);

function handleCategoryChanged(e){
if(e.target.value=="all") {
LoadProducts("http://fakestoreapi.com/products&quot;);
} else {
LoadProducts(`http://fakestoreapi.com/products/category/${e.target.value}`);
}
setCategory(e.target.value);
}

return(
<div className="container-fluid">
<header className="bg-dark text-white text-center p-2">
<h2><span className="bi bi-cart"></span> Shopper.</h2>
</header>
<section className="mt-3 row">
<nav className="col-2">
<div>
<label className="form-label">Select Category</label>
<div>
<select onChange={handleCategoryChanged} className="form-select">
{
categories.map(category=>
<option key={category} value={category}>
{category.toUpperCase()}
</option>
)
}
</select>
</div>
</div>
<div className="mt-3">
<label className="form-label">Choose Category</label>
<div>
<ul className="list-unstyled">
{
categories.map(cat=>
<li key={cat}>
<input type="radio" onChange={handleCategoryChanged} name="category"
value={category} /> {cat.toUpperCase()}
</li>
)
}
</ul>
</div>
</div>
</nav>
<main className="col-8 d-flex flex-wrap">
{
products.map(product=>
<div key={product.id} className="card m-2 p-2">
<img src={product.image} className="card-img-top" height="150" />
<div className="card-header">
<p>
{product.title}
</p>
</div>
<div className="card-body">
<dl>
<dt>Price</dt>
<dd>{product.price}</dd>
<dt>Rating</dt>
<dd>
<span className="bi bi-star-fill text-success"></span> {product.rating.rate}
[{product.rating.count}]
</dd>
</dl>
</div>
<div className="card-footer">
<button className="btn btn-danger">
<span className="bi bi-cart4"></span> Add to Cart
</button>
</div>
</div>
)
}
</main>
</section>
</div>
)
}

React Data Binding


- One Way Binding
- Two Way Binding
- Data from API
fetch(), jquery, axios

React Style and Class Binding


-----------------------------------------

- Style Binding is the process of configuring inline styles for any element dynamically.

<h1 style="border:1px solid red">

- JSX will not support CSS style attributes directly in any element.
- Styles can bind with HTML elements as JSON object.

Syntax:
<h1 style={ {propertyName:'value', propertyName:'value'} }>

Ex:
<h1 style={{color:'red', textAlign:'center'}}>

- Style binding allows to change the styles of any element dynamically.

Ex:
styledemo.component.js

import { useState } from "react";

export function StyleDemoComponent()


{
const [styleObject, setStyleObject] = useState({border:'', boxShadow:''});
const [userError, setUserError] = useState('');

function handleUserName(e){
if(e.target.value.charCodeAt(0)>=65 && e.target.value.charCodeAt(0)<=90) {
setStyleObject({
border: '2px solid green',
boxShadow: '2px 2px 3px green'
});
setUserError('');
} else {
setStyleObject({
border: '2px solid red',
boxShadow: '2px 2px 3px red'
});
setUserError('Name must start with uppercase letter');
}
}

return(
<div className="container-fluid">
<h2>Register User</h2>
<dl>
<dt>User Name</dt>
<dd><input type="text" style={styleObject} onBlur={handleUserName}/></dd>
<dd className="text-danger">{userError}</dd>
</dl>
</div>
)
}

Ex:
styledemo.component.js

import { useState } from "react";

export function StyleDemoComponent()


{

const [styleObject, setStyleObject] = useState({backgroundColor:'', textAlign:''});

function backgroundChange(e){
setStyleObject({
backgroundColor : e.target.value,
textAlign: styleObject.textAlign
});
}
function alignChange(e){
setStyleObject({
textAlign: e.target.value,
backgroundColor: styleObject.backgroundColor
});
}

return(
<div className="container-fluid">
<h2>Choose Styles</h2>
<dl>
<dt>Background Color</dt>
<dd>
<select onChange={backgroundChange}>
<option value="yellow">Yellow</option>
<option value="green">Green</option>
<option value="red">Red</option>
</select>
</dd>
<dt>Text Align</dt>
<dd>
<select onChange={alignChange}>
<option value="left">Left</option>
<option value="center">Center</option>
<option value="right">Right</option>
</select>
</dd>
</dl>
<h1 style={styleObject}>Sample Text</h1>
</div>
)
}

Class Binding
- It allows to bind any CSS class to HTML element.

<div className="cssClassName">

- Class Binding allows to change the class dynamically.

Ex:
styledemo.component.css

.dark-theme {
background-color: black;
color:white;
}

styledemo.component.js
import { useState } from "react";
import "./styledemo.component.css";

export function StyleDemoComponent()


{
const [theme, setTheme] = useState('');

function handleThemeChange(e){
if(e.target.checked) {
setTheme('dark-theme');
} else {
setTheme('');
}
}

return(
<div className="container-fluid d-flex justify-content-center align-items-center"
style={{height:'400px'}}>
<form className={theme}>
<div className="form-switch">
<input type="checkbox" onChange={handleThemeChange} className="form-check-
input"/> Dark Mode
</div>
<h3><span className="bi bi-person-fill"></span>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-dark w-100">Login</button>
</form>
</div>
)
}

Data Binding
Style Binding
Class Binding

Event Binding

Event Binding

FAQ: What is Event?


Ans:
- Event is a message sent by sender to its subscriber in order to notify the change.
- Event follows a software design pattern called "Observer".
- Event uses a delegate mechansim. [Function Pointer]

Syntax:
function InsertClick() => Subscriber
{
}

<button onclick="InsertClick()"> => Sender

- Sender sends a notification and subscriber performs the funcitonality.


- "Observer" is a communication pattern.
- JavaScript events are browser events
- React is not using DOM, it is using virtual DOM
- React uses a library called "SyntheticEvents".
- SyntheticEvents are mapped to Browser Event

SyntheticEvent BrowserEvent
onClick => onclick

- Synthetic Events are categories into various group based on their role and responsibility

1. Mouse Events
onMouseOver
onMouseOut
onMouseDown
onMouseUp
onMouseMove

2. Keyboard Events
onKeyUp
onKeyDown
onKeyPress

3. Button Events
onClick
onDblClick
onContextMenu

4. Form Events
onSubmit
onReset

5. Clipboard Events
onCut
onCopy
onPaste

6. Element State Events


onChange
onFocus
onBlur
onSelect
onSelectStart

7. Touch Events
onTouchStart
onTouchEnd
onTouchMove

8. Timer Events
setTimeout()
clearTimeout()
setInterval()
clearInterval()

Syntax:
function handleInsertClick()
{
}

<button onClick={handleInsertClick}> Insert </button>

onClick={handleInsertClick} => Event Handler


onClick => Event

- Event handler in function component will not have args.

Note: JavaScript event handle allows following args


a) Default args
this, event
b) Custom args
"", true, [], { }

this - sends information about current object.


event - sends information about current event

- React Synthetic event will not allow args in functional component.


- React Synthetic event can provide a reference which can access both object and event details.

function handleInsertClick(SyntheticEvent)
{
SyntheticEvent.EventArgs
SyntheticEvent.target.ObjectProperties
}

<button onClick={handleInsertClick}> Insert </button>

Ex:
Event-Demo.Component.js

export function EventDemoComponent(){

function InsertClick(SyntheticEvent)
{
document.write(`
Button Id : ${SyntheticEvent.target.id} <br>
Class Name: ${SyntheticEvent.target.className} <br>
X Position: ${SyntheticEvent.clientX} <br>
Ctrl Key : ${SyntheticEvent.ctrlKey}
`)
}
return(
<div className="container-fluid">
<h2>Events</h2>

<button id="btnInsert" onClick={InsertClick} className="btn btn-primary">Insert</button>


</div>
)

Ex:
Event-Demo.Component.js

import { useState } from "react"

export function EventDemoComponent(){

const [products] = useState([{Id:1, Name:"TV"},{Id:2, Name:"Mobile"}]);

function AddClick(e){
var result = products.find(product=> product.Id==e.target.id);
document.write(result.Name + "<br>" + result.Id);
}

return(
<div className="container-fluid">
<h2>Products</h2>
<div>
{
products.map(product=>
<div>
<p>{product.Name}</p>
<button id={product.Id} onClick={AddClick}> <span className="bi bi-cart4"></span> Add
to Cart</button>
</div>
)
}
</div>
</div>
)

Mouse Events

React Events
- What is Event?
- What is Event Handler?
- Event Args
- SyntheticEvents
MouseEvents
KeyboardEvents
ButtonEvents
TouchEvents
ElementState Events etc..

MouseEvents
onMouseOver
onMouseOut
onMouseDown
onMouseUp
onMouseMove

Event Args
clientX
clientY

Ex:
event-demo.component.js
import { useState } from "react"

export function EventDemoComponent(){

const [slide, setSlide] = useState("slide1.PNG");

function handleOver(){
setSlide('slide2.PNG');
}
function handleOut(){
setSlide('slide1.PNG');
}

return(
<div className="container-fluid">
<img src={slide} onMouseOver={handleOver} onMouseOut={handleOut} className="w-100"/>
<p>Move mouse over image</p>
</div>
)

Ex: Marquee

event-demo.component.js

import { useState } from "react"

export function EventDemoComponent(){

function StartMarquee(e){
e.target.start();
}
function StopMarquee(e){
e.target.stop();
}

return(
<div className="container-fluid">
<h2>Mouse Events</h2>
<marquee onMouseOver={StopMarquee} onMouseOut={StartMarquee} scrollamount="10">
<img src="asp.jpg" className="me-2" width="100" height="100"/>
<img src="dm.jpg" className="me-2" width="100" height="100"/>
<img src="ds.jpg" className="me-2" width="100" height="100"/>
</marquee>
</div>
)

Ex: Mouse Move

import { useState } from "react"

export function EventDemoComponent(){

const [styleObject, setStyleObject] = useState({position:'',top:'',left:''});

function GetPosition(e){
setStyleObject({
position: 'fixed',
top: e.clientY + 'px',
left: e.clientX + 'px'
})
}

return(
<div className="container-fluid" onMouseMove={GetPosition}>
<div style={{height:'1000px'}}>
<p>Move mouse pointer to test</p>
</div>
<img src="flag.gif" style={styleObject} width="50" height="50"/>
</div>
)

Ex: MouseOver Color Change

import { useState } from "react"

export function EventDemoComponent(){

const [shirt, setShirt] = useState('shirt.jpg');

function ChangeColor(e){
switch(e.target.id) {
case "red":
setShirt('redShirt.jpg');
break;
case "green":
setShirt('greenShirt.jpg');
break;
case "blue":
setShirt('blueShirt.jpg');
break;
}
}

return(
<div className="container-fluid">
<h2>T-Shirt</h2>
<img src={shirt} width="200" height="200"/>
<p className="mt-3">
<div>
<span id="red" onMouseOver={ChangeColor} style={{backgroundColor:'red', color:'white', cursor:
'grab'}} className="me-2 p-2">Red</span>
<span id="green" onMouseOver={ChangeColor} style={{backgroundColor:'green', color:'white',
cursor: 'grab'}} className="me-2 p-2">Green</span>
<span id="blue" onMouseOver={ChangeColor} style={{backgroundColor:'blue', color:'white',
cursor: 'grab'}} className="me-2 p-2">Blue</span>
</div>
</p>
</div>
)

KeyBoard Events
onKeyUp
onKeyDown
onKeyPress

Args
keyCode
charCode
which
shiftKey
ctrlKey
altKey

Ex: KeyEvents
event-demo.component.js

import { useState } from "react"

export function EventDemoComponent(){


const [users] = useState([{"UserId":"john"},{"UserId":"john12"},{"UserId":"david"}]);
const [msg, setMsg] = useState('');
const [errorClass, setErrorClass] = useState('');

function VerifyUserId(e){
for(var user of users)
{
if(user.UserId==e.target.value) {
setMsg('User Name Taken - Try Another');
setErrorClass('text-danger');
break;
} else {
setMsg('User Name Available');
setErrorClass('text-success');
}
}
}

return(
<div className="container-fluid">
<h2>Keyboard Events</h2>
<dl>
<dt>User Id</dt>
<dd><input type="text" onKeyUp={VerifyUserId} /></dd>
<dd className={errorClass}>{msg}</dd>
</dl>
</div>
)

Ex: KeyCode, charCode, which

import { useState } from "react"

export function EventDemoComponent(){

const [users] = useState([{"UserId":"john"},{"UserId":"john12"},{"UserId":"david"}]);


const [msg, setMsg] = useState('');
const [errorClass, setErrorClass] = useState('');
const [toggle, setToggle] = useState({display:'none'});

function VerifyUserId(e){
for(var user of users)
{
if(user.UserId==e.target.value) {
setMsg('User Name Taken - Try Another');
setErrorClass('text-danger');
break;
} else {
setMsg('User Name Available');
setErrorClass('text-success');
}
}
}

function VerifyPassword(e){
if((e.which >= 65 && e.which <= 90) || (e.keyCode >= 65 && e.keyCode<= 90)) {
setToggle({display:'block'});
} else {
setToggle({display:'none'});
}
}

return(
<div className="container-fluid">
<h2>Keyboard Events</h2>
<dl>
<dt>User Id</dt>
<dd><input type="text" onKeyUp={VerifyUserId} /></dd>
<dd className={errorClass}>{msg}</dd>
<dt>Password</dt>
<dd><input type="password" onKeyPress={VerifyPassword} /></dd>
<dd style={toggle} className="text-warning">
<span className="bi bi-exclamation-triangle"></span> Warning : Caps ON
</dd>
</dl>
</div>
)

Button Events
onClick
onDblClick
onContextMenu

Element State Events

onBlur
onFocus
onChange
onSelect
onSelectStart

Element State Events


onChange
onBlur
onFocus
onSelectStart

Ex:
import { useState } from "react"

export function EventDemoComponent(){

const [userName, setUserName] = useState('');


const [userError, setUserError] = useState('');
const [cityName, setCityName] = useState('');
const [cityError, setCityError] = useState('');

function handleUserName(e){
setUserName(e.target.value);
}

function SubmitClick(){
if(userName=="") {
setUserError("User Name Required");
} else {
document.write("Hello ! " + userName + " Your City is " + cityName);
}
if(cityName=="notcity") {
setCityError("Please Select Your City");
}
}
function handleUserBlur(){
if(userName=="") {
setUserError("User Name Required");
} else {
setUserError("");
}
}
function handleUserKeyUp(){
if(userName=="") {
setUserError("User Name Required");
} else {
setUserError("");
}
}
function CityChanged(e){
if(e.target.value=="notcity") {
setCityError("Please Select Your City");
} else {
setCityName(e.target.value);
setCityError("");
}
}
function UserFocus(){
setUserError("Name is Mandatory");
}

return(
<div className="container-fluid">
<h2>Register User</h2>
<dl>
<dt>User Name</dt>
<dd><input type="text" onFocus={UserFocus} onKeyUp={handleUserKeyUp}
onBlur={handleUserBlur} onChange={handleUserName}/></dd>
<dd className="text-danger">{userError}</dd>
<dt>Your City</dt>
<dd>
<select onChange={CityChanged}>
<option value="notcity">Select City</option>
<option value="Delhi">Delhi</option>
<option value="Hyderabad">Hyd</option>
<option value="Chennai">Chennai</option>
</select>
</dd>
<dd className="text-danger">{cityError}</dd>
</dl>
<button onClick={SubmitClick}>Submit</button>
</div>
)

Clipboard Events
- onCut
- onCopy
- onPaste

Ex:
import { useState } from "react"

export function EventDemoComponent(){


const [userName, setUserName] = useState('');
const [userError, setUserError] = useState('');
const [cityName, setCityName] = useState('');
const [cityError, setCityError] = useState('');
const [msg, setMsg] = useState('');

function handleUserName(e){
setUserName(e.target.value);
}

function SubmitClick(){
if(userName=="") {
setUserError("User Name Required");
} else {
document.write("Hello ! " + userName + " Your City is " + cityName);
}
if(cityName=="notcity") {
setCityError("Please Select Your City");
}
}
function handleUserBlur(){
if(userName=="") {
setUserError("User Name Required");
} else {
setUserError("");
}
}
function handleUserKeyUp(){
if(userName=="") {
setUserError("User Name Required");
} else {
setUserError("");
}
}

function CityChanged(e){
if(e.target.value=="notcity") {
setCityError("Please Select Your City");
} else {
setCityName(e.target.value);
setCityError("");
}
}
function UserFocus(){
setUserError("Name is Mandatory");
}

function handleCut(){
setMsg("Removed and Placed on Clipboard");
}
function handleCopy(){
setMsg("Copied to Clipboard");
}
function handlePaste(){
setMsg("Inserted from Clipboard");
}

return(
<div className="container-fluid">
<h2>Register User</h2>
<dl>
<dt>User Name</dt>
<dd><input type="text" onFocus={UserFocus} onKeyUp={handleUserKeyUp}
onBlur={handleUserBlur} onChange={handleUserName}/></dd>
<dd className="text-danger">{userError}</dd>
<dt>Your City</dt>
<dd>
<select onChange={CityChanged}>
<option value="notcity">Select City</option>
<option value="Delhi">Delhi</option>
<option value="Hyderabad">Hyd</option>
<option value="Chennai">Chennai</option>
</select>
</dd>
<dd className="text-danger">{cityError}</dd>
<dt>Mobile</dt>
<dd><input type="text" onCut={handleCut} onCopy={handleCopy} onPaste={handlePaste}
/></dd>
<dd>{msg}</dd>
</dl>
<button onClick={SubmitClick}>Submit</button>
</div>
)

Touch Events
-onTouchStart
-onTouchEnd
-onTouchMove

Ex:
import { useState } from "react"

export function EventDemoComponent(){


const [styleObject, setStyleObject] = useState({position:'', left:'', top:''});

function GetPosition(e){
setStyleObject({
position: 'fixed',
left: e.touches[0].clientX + 'px',
top: e.touches[0].clientY + 'px'
});
}

return(
<div className="container-fluid">
<p>Drag and Drop with your touch</p>
<img style={styleObject} onTouchMove={GetPosition} src="shirt.jpg" width="100" height="100"/>
</div>
)

Ex:
import { useState } from "react"

export function EventDemoComponent(){

const [msg, setMsg] = useState('');

function SelectedCourse(e){
switch(e.target.id){
case "asp":
setMsg("ASP.NET is used for building Server Side Web Apps");
break;
case "aws":
setMsg("AWS is cloud service.");
break;
case "dm":
setMsg("Someting about Digital Marketing..");
break;
}
}

return(
<div className="container-fluid">
<p>Touch the Course banner to view details</p>
<div className="mt-3">
<img id="asp" onTouchStart={SelectedCourse} src="asp.jpg" width="100" height="100"/>
<img id="aws" onTouchStart={SelectedCourse} src="aws.jpg" width="100" height="100"/>
<img id="dm" onTouchStart={SelectedCourse} src="dm.jpg" width="100" height="100"/>
</div>
<p>{msg}</p>
</div>
)

Ex:
import { useState } from "react"

export function EventDemoComponent(){

const [styleObject, setStyleObject] = useState({width: '', height: ''});

function ZoomImage(){
setStyleObject({
width: '400px',
height: '400px'
});
}
function ZoomOut(){
setStyleObject({
width: '100px',
height: '100px'
});
}

return(
<div className="container-fluid">
<div onTouchEnd={ZoomOut} className="d-flex justify-content-center align-items-center"
style={{height:'500px'}}>
<img style={styleObject} onTouchStart={ZoomImage} src="asp.jpg" width="100" height="100"/>
</div>
</div>
)

Form Events
- onSubmit
- onReset

Ex:
import { useState } from "react"

export function EventDemoComponent(){


function SubmitClick(e){
e.preventDefault();
alert("Form Submitted");
}

return(
<div className="container-fluid">
<form onSubmit={SubmitClick}>
<dl>
<dt>User Name</dt>
<dd><input type="text" name="Username"/></dd>
</dl>
<button>Submit</button>
</form>
</div>
)

Note: You can prevent default functionality for any element by using the event args "e.preventDefault()".

Timer Events
setTimeOut()
clearTimeOut()
setInterval()
clearInterval()

- setTimeOut() defines the delay time for any task in memory.


Task the removed from memory and sent into process.

- clearTimeOut() removes any task from memory before it is


released into process.

Ex:
import { useState } from "react"

export function EventDemoComponent(){

const [msg, setMsg] = useState('');

function Message1(){
setMsg('Hello !');
}
function Message2(){
setMsg('How are you?');
}
function Message3(){
setMsg('Welcome to React');
}

var m1, m2, m3;

function HandleClick(){
m1 = setTimeout(Message1, 2000);
m2 = setTimeout(Message2, 4000);
m3 = setTimeout(Message3, 8000);
}
function CancelClick(){
clearTimeout(m2);
}

return(
<div className="container-fluid">
<button onClick={HandleClick}>Show Message</button>
<button onClick={CancelClick}>Cancel Message-2</button>
<h2 className="text-center">{msg}</h2>
</div>
)
}

setInterval() It loads the task into memory and releases into process without
deleting from memory.
The task can execute at regular time intervals.

clearInterval() It is used to remove the task from memory.

setTimeout()
clearTime()
setInterval()
clearInterval()

Ex:
import { useEffect, useState } from "react"

export function EventDemoComponent(){

const [time, setTime] = useState();

function LoadTime(){
var now = new Date();
setTime(now.toLocaleTimeString());
}
var timer;

useEffect(()=>{
timer = setInterval(LoadTime,1000);
},[]);

function handleStopClick(){
alert("Stop Clicked");
clearInterval(timer);
}

return(
<div className="container-fluid">
<div className="text-center">
<h2 className="mt-4">{time}</h2>
<button onClick={handleStopClick} className="me-2">
<span className="bi bi-stop-fill"></span>
</button>
<button>
<span className="bi bi-play-fill"></span>
</button>
</div>
</div>
)
}

Ex: EMI Calculator - EMI Formula

import { useState } from "react";

export function EmiCalculatorComponent(){

const [amount, setAmount] = useState(0);


const [years, setYears] = useState(0);
const [rate, setRate] = useState(0);
const [emi, setEmi] = useState(0);

function AmountChange(e){
setAmount(e.target.value);
}
function YearChange(e) {
setYears(e.target.value);
}
function RateChange(e){
setRate(e.target.value);
}
function CalculateClick(){
var principal = amount;
var r = rate/(12*100);
var n = years * 12;
var emi = (principal * r * Math.pow(r+1,n))/(Math.pow(1+r,n)-1);
setEmi(emi);
}

return(
<div className="container-fluid">
<h2>Pesonal Loan EMI Calculator</h2>
<div className="row mt-4 border border-dark border-2 p-4 m-3">
<div className="col">
Amount you need &#8377; <input type="text" value={amount} />
</div>
<div className="col">
for <input type="text" value={years} size="4"/> years
</div>
<div className="col">
Interest rate <input type="text" value={rate} size="4" /> %
</div>
</div>
<div className="row mt-4 border border-dark border-2 p-4 m-3">
<div className="col">
&#8377; 50,000 <input type="range" onChange={AmountChange} min="50000"
max="1000000"/> &#8377; 10,00,000
</div>
<div className="col">
1 <input type="range" onChange={YearChange} min="1" max="5" /> 5
</div>
<div className="col">
10.25% <input type="range" onChange={RateChange} min="10.25" max="18.25" step="0.1" />
18.25%
</div>
</div>
<div className="mt-3" >
<div className="row">
<div className="col text-center">
<button onClick={CalculateClick} className="btn btn-primary">Calculate</button>
</div>
</div>
</div>
<div className="mt-3">
<h3 className="text-center">Your montly installment is &#8377; {Math.round(emi)} for Amount
&#8377;{amount} with Rate {rate}%</h3>
</div>
</div>
)
}
Task: BMI Calculator

import { useState } from "react";

export function SampleComponent()


{
const [gender, setGender] = useState('');
const [selectedGender, setSelectedGender] = useState('');

function MaleChange(e){
if(e.target.checked) {
setGender(e.target.value);
}
}
function FemaleChange(e){
if(e.target.checked) {
setGender(e.target.value);
}
}

function DetailsClick(){
setSelectedGender(gender);
}

return(
<div className="container-fluid">
<h2>Radio</h2>
<input type="radio" onChange={MaleChange} name="gender" value="Male" /> Male
<input type="radio" onChange={FemaleChange} name="gender" value="Female"/> Female
<br/>
<button onClick={DetailsClick}>Get Details</button>
<p>You selected Gender : {selectedGender}</p>
</div>
)
}

Ex: Slider

import { useState } from "react";

export function SampleComponent()


{

return(
<div className="container-fluid">
<h2>Slider</h2>
<div className="progress">
<div className="progress-bar me-1 bg-dark" style={{width:'25%'}}>
Low Weight &lt; 53 kg
</div>
<div className="progress-bar me-1 bg-info" style={{width:'25%'}}>
Normal Weight
</div>
<div className="progress-bar me-1 bg-dark" style={{width:'25%'}}>
OverWeight
</div>
<div className="progress-bar bg-dark" style={{width:'25%'}}>
Obese
</div>
</div>
<div>
<span style={{marginLeft:'35%'}} className="bi bi-triangle-fill"></span>
</div>
</div>
)
}

Component Properties
- Components a build-blocks for application.
- Component provides reusable and customized template.
- Every component is reusable but can't be customized.
- To allow customization of component, you have to use "Properties".
- Every component can have properties.
- Properties are used to modify the component.

Ex: Function
- A function can be parameter less.
- A parameter less function will do the same task everytime.
- A parameterized function can change according to state and situation.

- Component parameters are called as "Properties".

<h1 align="center"> align is a property of h1 component


<table border="1">

Syntax:
export function Name(props)
{
return(
<div>{props.ref}</div>
);
}

<Name ref="value">
Ex:
1. Add a new component with props

login.component.js

import './login.component.css';
export function LoginComponent(props)
{
return(
<div id="form-container" className="container-fluid">
<form>
<h2> <span className="bi bi-person-fill"></span> {props.title}</h2>
<div className="mb-2">
<label className="form-label">{props.login_id}</label>
<div>
<input type={props.login_type} className="form-control" />
</div>
</div>
<div className="mb-2">
<label className="form-label">Password</label>
<div>
<input type="password" className="form-control" />
</div>
</div>
<div className="mb-2">
<button className="btn btn-primary w-100">Login</button>
</div>
</form>
</div>
)
}

login.component.css

form {
width: 300px;
border:2px solid gray;
padding: 20px;
border-radius: 20px;
}
#form-container {
display: flex;
justify-content: center;
align-items: center;
height: 500px;
}

2. Add another component to use login


properties.component.js

import { LoginComponent } from "../login/login.component";

export function PropertiesComponent(){


return(
<div className="container-fluid">
<LoginComponent title="Admi Login" login_id="Email" login_type="email" />
</div>
)
}

Ex:
Grid.component.js

export function GridComponent(props){


return(
<div className="container-fluid">
<table style={{backgroundColor:props.theme}} className="table table-hover caption-top">
<caption>{props.title}</caption>
<thead>
<tr>
{
props.fields.map(field=>
<th key={field}>{field}</th>
)
}
</tr>
</thead>
<tbody>
{
props.data.map(item=>
<tr key={item.Name}>
{
Object.keys(item).map(key=>
<td key={item[key]}>{item[key]}</td>
)
}
</tr>
)
}
</tbody>
</table>
</div>
)
}

properties.component.js

import { useState } from "react";


import { GridComponent } from "../grid/grid.component";

export function PropertiesComponent(){


const [products] = useState([{Name:"TV", Price:45000.33, Stock:"Available", Qty:3}, {Name:"Shoe", Price:
5000.33, Stock:"Out of Stock", Qty:4}]);
return(
<div className="container-fluid">
<GridComponent theme="yellow" title="Employee Grid" fields={["Name", "Designation", "Salary"]}
data={[{Name:"John", Designation:"Manager", Salary:45000.44},{Name:"David", Designation:"Developer",
Salary:23000.44}]} />
<GridComponent theme="green" title="Products Grid" fields={["Name","Price","Stock", "Qty"]}
data={products} />
</div>
)
}

Conditional Rendering

Summary
- React Components
- Function Components
- Data Binding
- Event Binding
- Class and Style Binding
- Properties
Conditional Rendering
- A component template can change according to state and situation.

Ex:
function Name()
{
if(condition) {
return value1;
}
else {
return value2;
}
}

Ex:
1. template-demo.component.js

export function TemplateDemoComponent(props){


if(props.layout=="horizontal") {
return(
<div>
<nav>
<span className="me-4">Facebook</span>
<span className="me-4">Twitter</span>
<span className="me-4">Instagram</span>
</nav>
</div>
)
} else {
return(
<div>
<nav>
<div className="mb-3 bi bi-facebook"></div>
<div className="mb-3 bi bi-twitter"></div>
<div className="mb-3 bi bi-instagram"></div>
<div className="mb-3 bi bi-linkedin"></div>
</nav>
</div>
)
}
}

2. properties.component.js

import { useState } from "react";


import { TemplateDemoComponent } from "../template-demo/template-demo.component";

export function PropertiesComponent(){


const [orientation, setOrientation] = useState('');
function LayoutChange(e){
if(e.target.value=="horizontal") {
setOrientation(e.target.value);
} else {
setOrientation("vertical");
}
}
return(
<div className="container-fluid">
<h2>Conditional Rendering</h2>
<div className="mb-2">
<select onChange={LayoutChange}>
<option value="-1">Select Layout</option>
<option value="horizontal">Horizontal</option>
<option value="vertical">Vertical</option>
</select>
</div>
<TemplateDemoComponent layout={orientation} />
</div>
)
}
Class Components
- What is JavaScript Class?
- Class Members
- Inheritance
- Polymorphism
- You can use JavaScript class for designing a component.

Syntax:
export class Name
{
}

- Every component class gets the behaviour of component by extending "React.Component" base class.

Syntax:
export class Name extends React.Component
{
}

- Class component returns a fragment by using "render()".


- "render()" is of type "React.Node"
- React.Node creates and add element into Virtual DOM.
- "render()" must have return statement.

Syntax:
export class Name extends React.Component
{
render(){
return(
<React.Fragment> </React.Fragment>
)
}
}

Data Binding in Class Component


-----------------------------------------------

- Class can store data in property.


- You can access the property within class by using "this" keyword.

Ex: register.component.js

import React from "react";

export class RegisterComponent extends React.Component


{
Title = "User Register";
render(){
return(
<div className="container-fluid">
<h2>{this.Title}</h2>
</div>
)
}
}

- Component class properties are immutable.


- You have to handle data by using state.

FAQ: Can we use "useState()" hook in class component?


Ans: No. Hooks are only for functions.

FAQ: Why useState can't be used in class component?


Ans: useState is a function, class can't have function as class member.

FAQ: How to handle state in class component?


Ans: "React.Component" base class defines implicit state.

- Every class component in react is defined with built in state. Hence class components are also called as
"Statefull components".

- State must be configured in constructor() of component class.


- State is object type.

Syntax:
constructor()
{
super();
this.state = {
key : value - any type
}
}
<p> { this.state.key } </p>
Ex:
register.component.js

import React from "react";

export class RegisterComponent extends React.Component


{
constructor(){
super();
this.state = {
title: 'Product Details',
product: {
Name: "TV",
Price: 45000.44,
Stock: true
},
categories: ["All", "Electronics", "Footwear"]
}
}
render(){
return(
<div className="container-fluid">
<h2>{this.state.title}</h2>
<dl>
<dt>Name</dt>
<dd>{this.state.product.Name}</dd>
<dt>Price</dt>
<dd>{this.state.product.Price}</dd>
<dt>Stock</dt>
<dd>
{(this.state.product.Stock==true)?"Available":"Out of Stock"}
</dd>
</dl>
<h3>Select Category</h3>
<select>
{
this.state.categories.map(category=>
<option key={category}>{category}</option>
)
}
</select>
</div>
)
}
}

- If you want to store any data into state then you have to defined by using the method "setState()".
Class and Style Binding
- It is same as function component.

Event Binding in Class Component


- All events are same
- Event handlers are same
- Event args are same
- Class event uses a class method, not function.

Syntax:
handleClick() {

}
<button onClick={this.handleClick}> </button>

Ex:
import React from "react";

export class RegisterComponent extends React.Component


{
constructor(){
super();
this.state = {
title: 'Product Details',
product: {
Name: "TV",
Price: 45000.44,
Stock: true
},
categories: ["All", "Electronics", "Footwear"],
effect : 'text-success'
}
}

handleCategoryChange(e){
alert(e.target.value);
}

render(){
return(
<div className="container-fluid">
<h2>{this.state.title}</h2>
<dl>
<dt className={this.state.effect}>Name</dt>
<dd>{this.state.product.Name}</dd>
<dt>Price</dt>
<dd>{this.state.product.Price}</dd>
<dt>Stock</dt>
<dd>
{(this.state.product.Stock==true)?"Available":"Out of Stock"}
</dd>
</dl>
<h3>Select Category</h3>
<select onChange={this.handleCategoryChange}>
{
this.state.categories.map(category=>
<option key={category}>{category}</option>
)
}
</select>
</div>
)
}
}

Event Binding in Class Component


- Events are same as Synthetic Events.
- Event args are same.
- Handler uses delgate mechanism to methods.

methodName() {

<button onClick={this.methodName}> </button>

- Event handler in class component must bind to class in order to use state.
- There are 2 ways

constructor()
{
this.handleChange = this.handleChange.bind(this);
}
(or)

<select onChange={this.handleChange.bind(this)}> </select>

Ex:
import React from "react";

export class RegisterComponent extends React.Component


{
constructor(){
super();
this.state = {
Name: '',
Price: 0,
City: ''
}
this.handleNameChange = this.handleNameChange.bind(this);
this.handleCityChange = this.handleCityChange.bind(this);
this.handleRegisterClick = this.handleRegisterClick.bind(this);
}

handleNameChange(e){
this.setState({
Name: e.target.value,
Price: this.state.Price,
City: this.state.City
});
}
handlePriceChange(e){
this.setState({
Name: this.state.Name,
Price: e.target.value,
City: this.state.City
})
}
handleCityChange(e) {
this.setState({
Name: this.state.Name,
Price: this.state.Price,
City: e.target.value
})
}

handleRegisterClick(){
alert(JSON.stringify(this.state));
}

render(){
return(
<div className="container-fluid">
<div className="row">
<div className="col-3">
<dl>
<dt>Name</dt>
<dd><input type="text" onChange={this.handleNameChange}
className="form-control"/></dd>
<dt>Price</dt>
<dd><input type="text" onChange={this.handlePriceChange.bind(this)} className="form-
control"/></dd>
<dt>City</dt>
<dd>
<select onChange={this.handleCityChange} className="form-select">
<option>Delhi</option>
<option>Hyd</option>
</select>
</dd>
</dl>
<button onClick={this.handleRegisterClick} className="btn btn-primary
w-100">Register</button>
</div>
<div className="col-9">
<dl>
<dt>Name</dt>
<dd>{this.state.Name}</dd>
<dt>Price</dt>
<dd>{this.state.Price}</dd>
<dt>City</dt>
<dd>{this.state.City}</dd>
</dl>
</div>
</div>
</div>
)
}
}

FAQ: If you can't use hooks in class component then how to handle useEffects?
Ans: By using component life cycle hooks.

Component Life Cycle Hooks


- Every class component have 3 phases
1. Mount
2. Update
3. Unmount
- Mount
* Component is created
* Library for component is loaded
* State is configured
* Values can be initialized into state
* It is managed by a method
"ComponentDidMount()"

- Update
* Style Binding
* Class Binding
* Data Binding
* Event Binding
* It is managed by a method
"ComponentWillUpdate()"

- Unmount
* All events are unsubscribed
* Memory allocated for component is destroyed
* Unmount phase will fireup when another component is requested.

Ex:
lifecycle.component.js

import React from "react";

class LoginComponent extends React.Component {

componentDidMount(){
alert("Login Component Requested");
}
componentWillUnmount(){
alert("Login Component will unmount");
}

render(){
return(
<div>
<h2>Login</h2>
</div>
)
}
}
class RegisterComponent extends React.Component {
componentDidMount(){
alert("Register Component Requested");
}
componentWillUnmount(){
alert("Register Component will unmount");
}
render(){
return(
<div>
<h2>Register</h2>
</div>
)
}
}

export class LifeCycleComponent extends React.Component


{
constructor(){
super();
this.state = {
component: ''
}
this.handleLoginClick = this.handleLoginClick.bind(this);
this.handleReigsterClick = this.handleReigsterClick.bind(this);
}

handleLoginClick(){
this.setState({
component: <LoginComponent />
})
}
handleReigsterClick(){
this.setState({
component: <RegisterComponent />
})
}

render(){
return(
<div className="container">
<h2>Life Cycle Hooks</h2>
<div>
<button onClick={this.handleLoginClick}>Login</button>
<button onClick={this.handleReigsterClick}>Register</button>
</div>
<hr />
<div>
{this.state.component}
</div>
</div>
)
}
}

FAQ: How mount and unmount is managed in function component?


Ans : useEffect()

Syntax:
useEffect(()=>{

.... actions on mount.....


return {
actions on unmount..
}

},[])
Shopping with Class
- Forms and Validations

ReactBasicFlow.png
Image

Form and Validations


- React uses lot of functions and events to handle forms and validation.
- Validation is the process of verifying user input.
- Validation is required to ensure that contradictionary and unauthorized data is not get stored into
database.

Ex: React Form and Validation with react native style

formvaidation.component.js

import { useState } from "react"

export function FormValidationComponent()


{
const [userDetails, setUserDetails] = useState({UserName:'', Age:0, Mobile: '', City:''});
const [nameError, setNameError] = useState('');
const [ageError, setAgeError] = useState('');
const [mobileError, setMobileError] = useState('');
const [cityError, setCityError] = useState('');

function NameChange(e){
setUserDetails({
UserName: e.target.value,
Age: userDetails.Age,
Mobile: userDetails.Mobile,
City: userDetails.City
})
if(userDetails.UserName!==""){
setNameError("");
}
}
function AgeChange(e){
setUserDetails({
UserName: userDetails.UserName,
Age: e.target.value,
Mobile: userDetails.Mobile,
City: userDetails.City
})
if(userDetails.Age!==""){
setAgeError("");
}
if(isNaN(userDetails.Age)){
setAgeError("Age must be a number");
} else {
setAgeError("");
}
}
function MobileChange(e){
setUserDetails({
UserName: userDetails.UserName,
Age: userDetails.Age,
Mobile: e.target.value,
City: userDetails.City
})
}
function CityChange(e){
setUserDetails({
UserName: userDetails.UserName,
Age: userDetails.Age,
Mobile: userDetails.Mobile,
City: e.target.value
})
}

function FormSubmit(e){
e.preventDefault();
if(userDetails.UserName==""){
setNameError("User Name Required");
}
if(userDetails.Age==""){
setAgeError("Age Required");
} else {
if(isNaN(userDetails.Age)){
setAgeError("Age must be a number");
}
}
if(userDetails.Mobile.match(/\+91\d{10}/)){
setMobileError("");
} else {
setMobileError("Invalid Mobile : 91+ and 10 digits");
}
if(userDetails.City=="-1"){
setCityError("Please Select your city");
} else {
setCityError("");
}
}

return(
<div className="container-fluid mt-3">
<form onSubmit={FormSubmit}>
<h2>Register User</h2>
<dl>
<dt>Name</dt>
<dd><input onChange={NameChange} type="text"/></dd>
<dd className="text-danger">{nameError}</dd>
<dt>Age</dt>
<dd><input onChange={AgeChange} type="text"/></dd>
<dd className="text-danger">{ageError}</dd>
<dt>Mobile</dt>
<dd><input onChange={MobileChange} type="text"/></dd>
<dd className="text-danger">{mobileError}</dd>
<dt>City</dt>
<dd>
<select onChange={CityChange}>
<option value="-1">Select Your City</option>
<option value="Delhi">Delhi</option>
<option value="Hyd">Hyd</option>
</select>
</dd>
<dd className="text-danger">{cityError}</dd>
</dl>
<button className="btn btn-primary">Submit</button>
</form>
</div>
)
}

3rd Party Forms


- Telerik and Kendo Forms
- Formik
- DevExpress Forms etc..

Formik Forms
> npm install formik --save

Ex:
1. Import formik base class

import { useFormik } from "formik";

2. Create a reference for formik


const formik = useFormik({
..formik properties...
})

3. formik properties

initialValues : configures the form data


handleBlur : configure actions on element blur
handleChange : configure actions on element value change
handleSubmit : defines actions to perform when form submitted
validate : It uses validation function that returns validation errors
validationSchema : It uses pre-defined validation services

Ex: Submitting form data using Formik

formkidemo.component.js

import { useFormik } from "formik";

export function FormikDemoComponent()


{
const formik = useFormik({
initialValues : {
UserName: '',
Age: 0,
Mobile: '',
City:''
},
onSubmit : (values) => {
alert(JSON.stringify(values));
}
})

return(
<div className="container-fluid mt-3">
<form onSubmit={formik.handleSubmit}>
<h2>Register User</h2>
<dl>
<dt>Name</dt>
<dd><input name="UserName" onChange={formik.handleChange} type="text"/></dd>
<dt>Age</dt>
<dd><input name="Age" onChange={formik.handleChange} type="text"/></dd>
<dt>Mobile</dt>
<dd><input name="Mobile" onChange={formik.handleChange} type="text"/></dd>
<dt>City</dt>
<dd>
<select name="City" onChange={formik.handleChange} >
<option value="-1">Select Your City</option>
<option value="Delhi">Delhi</option>
<option value="Hyd">Hyd</option>
</select>
</dd>
</dl>
<button className="btn btn-primary">Submit</button>
</form>
</div>
)
}

Formik Validation
- Formik can use validation function or validation schema for verifying values.
- Function is configured and designed by developer.
- Schema is configured by using another 3rd party called "Yup"

Validation Function:

function VerifyUserDetails(formData)
{
var errors = { };
logic for verifying form data
return errors;
}

const formik = useFormik({


initialValues : { },
validate : VerifyUserDetails

})

<div> { formik.errors.FieldName } </div>

Ex:
import { useFormik } from "formik";

export function FormikDemoComponent()


{

function VerifyUserDetails(formData)
{
var errors = {};

if(formData.UserName=="")
{
errors.UserName = "User Name Required";
} else if(formData.UserName.length<4) {
errors.UserName = "Name too short min 4 chars";
} else if(formData.UserName.length>10) {
errors.UserName = "Name too long max 10 chars";
}

if(formData.Age=="") {
errors.Age = "Age Required";
} else if (isNaN(formData.Age)) {
errors.Age = "Age must be a number";
}

if(formData.Mobile.match(/\+91\d{10}/)) {
errors.Mobile = "";
} else {
errors.Mobile = "Invalid Mobile +91 and 10 digits";
}

if(formData.City=="-1") {
errors.City = "Please Select your city";
} else {
errors.City = "";
}

return errors;
}

const formik = useFormik({


initialValues : {
UserName: '',
Age: 0,
Mobile: '',
City:''
},
validate: VerifyUserDetails,
onSubmit : (values) => {
alert(JSON.stringify(values));
}
})

return(
<div className="container-fluid mt-3">
<form onSubmit={formik.handleSubmit}>
<h2>Register User</h2>
<dl>
<dt>Name</dt>
<dd><input name="UserName" onChange={formik.handleChange} type="text"/></dd>
<dd className="text-danger">{formik.errors.UserName}</dd>
<dt>Age</dt>
<dd><input name="Age" onChange={formik.handleChange} type="text"/></dd>
<dd className="text-danger">{formik.errors.Age}</dd>
<dt>Mobile</dt>
<dd><input name="Mobile" onChange={formik.handleChange} type="text"/></dd>
<dd className="text-danger">{formik.errors.Mobile}</dd>
<dt>City</dt>
<dd>
<select name="City" onChange={formik.handleChange} >
<option value="-1">Select Your City</option>
<option value="Delhi">Delhi</option>
<option value="Hyd">Hyd</option>
</select>
</dd>
<dd className="text-danger">
{formik.errors.City}
</dd>
</dl>
<button className="btn btn-primary">Submit</button>
</form>
</div>
)
}

Validation Schema using Yup


- Yup is a libray for formik to define validation schema.
- It provides built in validation functions for verifying data type and value.

> npm install yup --save

Syntax:
import required, mix, max, pattern from "yup"
import * as yup from "yup";

const formik = useFormik({


initialValue: { },
validationSchema: yup.object({
FieldName: yup.required("Name Required")
.min(4, "")
.max(10, "")
.pattern()
.string()
})
})

- ValidationSchema of formik will return same "errors" object.

Ex:
import { useFormik } from "formik";
import * as yup from "yup";

export function FormikDemoComponent()


{

const formik = useFormik({


initialValues : {
UserName: '',
Age: 0,
Mobile: '',
City:''
},
onSubmit : (values) => {
alert(JSON.stringify(values));
},
validationSchema : yup.object({
UserName : yup.string()
.required("User Name Required")
.min(4, "Name too short min 4 chars")
.max(10, "Name too long max 10 chars"),
Age : yup.number()
.required("Age Required"),

Mobile : yup.string()
.matches(/\+91\d{10}/,"Invalid Mobile")
.required("Mobile Required")
})
})

return(
<div className="container-fluid mt-3">
<form onSubmit={formik.handleSubmit}>
<h2>Register User</h2>
<dl>
<dt>Name</dt>
<dd><input name="UserName" onChange={formik.handleChange} type="text"/></dd>
<dd className="text-danger">{formik.errors.UserName}</dd>
<dt>Age</dt>
<dd><input name="Age" onChange={formik.handleChange} type="text"/></dd>
<dd className="text-danger">{formik.errors.Age}</dd>
<dt>Mobile</dt>
<dd><input name="Mobile" onChange={formik.handleChange} type="text"/></dd>
<dd className="text-danger">{formik.errors.Mobile}</dd>
<dt>City</dt>
<dd>
<select name="City" onChange={formik.handleChange} >
<option value="-1">Select Your City</option>
<option value="Delhi">Delhi</option>
<option value="Hyd">Hyd</option>
</select>
</dd>
<dd className="text-danger">
{formik.errors.City}
</dd>
</dl>
<button className="btn btn-primary">Submit</button>
</form>
</div>
)
}

Formik Components
- Formik provides pre-defined components for form and validation.
<Formik>
<Form>
<Field>
<ErrorMessage>
- Component provides template design and functionality.
- It is clean in separation and error handling.

Syntax:
<Formik>
<Form>
<Field> </Field>
<ErrorMesage> </ErrorMessage>
</Form>
</Formik>

- Formik component provides properties

<Formik initialValues={} onSubmit={} validationSchema={}>


</Formik>

Formik with HTML elements


Formik with Formik components

Formik with HTML elements


1. Configure formik with "useFormik" hook
2. Configure validation schema with "yup".
3. Bind the fomik values with HTML elements by using
{...formik.getFieldProps("FieldName") }

4. Error Message is binded by using


{formik.errors.FieldName}
Ex:
import { useFormik } from "formik";
import * as yup from "yup";

export function FormikValidation(){


const formik = useFormik({
initialValues: {
UserName:"",
Age:0,
Mobile:""
},
validationSchema: yup.object({
UserName: yup.string()
.required("User Name Required")
.min(4, "Name too short min 4 chars")
.max(10, "Name too long max 10 chars"),
Age: yup.number()
.required("Age Required"),
Mobile: yup.string()
.required("Mobile Required")
.matches(/\+91\d{10}/, "Invalid Mobile +91 and 10 digits")
}),
onSubmit : (values)=> {
alert(JSON.stringify(values));
}
})
return(
<div className="container-fluid">
<h2>Register</h2>
<form onSubmit={formik.handleSubmit}>
<dl>
<dt>User Name</dt>
<dd><input name="UserName" {...formik.getFieldProps("UserName")} type="text" /></dd>
<dd className="text-danger">{formik.errors.UserName}</dd>
<dt>Age</dt>
<dd><input name="Age" {...formik.getFieldProps("Age")} type="text"/></dd>
<dd className="text-danger">{formik.errors.Age}</dd>
<dt>Mobile</dt>
<dd><input name="Mobile" {...formik.getFieldProps("Mobile")} type="text"/></dd>
<dd className="text-danger">{formik.errors.Mobile}</dd>
</dl>
<button>Register</button>
</form>
</div>
)
}

Formik validation with Formik Components


<Formik>
<Form>
<Field>
<ErrorMessage>

Syntax:
<Formik initialValues={} validationSchema={} onSubmit={ }>
{
<Form>
<Field name="FieldName" type="text" />
<Field as="select">
<option></option>
</Field>
<ErrorMessage name="FieldName" />
</Form>
}
</Formik>

Ex:

import { Formik, useFormik, Form, Field, ErrorMessage } from "formik";


import * as yup from "yup";

export function FormikComponents(){


function CityChange(e){
alert(e.target.value);
}
return(
<div className="container-fluid">
<h2>Register User</h2>
<Formik
initialValues={
{
UserName:"",
Age:0,
Mobile:""
}
}
validationSchema={
yup.object({
UserName: yup.string()
.required("User Name Required")
.min(4, "Name too short min 4 chars")
.max(10, "Name too long max 10 chars"),
Age: yup.number()
.required("Age Required"),
Mobile: yup.string()
.required("Mobile Required")
.matches(/\+91\d{10}/, "Invalid Mobile +91 and 10 digits")
})
}
onSubmit= {
(values)=> {
alert(JSON.stringify(values));
}
}
>
{
<Form>
<dl>
<dt>User Name</dt>
<dd>
<Field name="UserName" type="text"/>
</dd>
<dd className="text-danger" >
<ErrorMessage name="UserName"/>
</dd>
<dt>Age</dt>
<dd>
<Field type="text" name="Age" />
</dd>
<dd className="text-danger" >
<ErrorMessage name="Age" />
</dd>
<dt>Mobile</dt>
<dd>
<Field name="Mobile" type="text" />
</dd>
<dd className="text-danger">
<ErrorMessage name="Mobile" />
</dd>
<dt>City</dt>
<dd>
<Field as="select" onChange={CityChange}>
<option>Delhi</option>
<option>Hyd</option>
</Field>
</dd>
</dl>
<button>Register</button>
</Form>
}
</Formik>
</div>
)
}
Formik provides Form properties
- Form properties are used to know the status of form.
- You can access form properties from <Form> component

Syntax:
<Formik initialValues={} validationSchema={} onSubmit={}>
{
props => <Form> </Form>
}
</Formik>

props.isValid : true/false [all fields are valid]


props.dirty : true/false [modified]

EX:

import { Formik, useFormik, Form, Field, ErrorMessage } from "formik";


import * as yup from "yup";

export function FormikComponents(){


function CityChange(e){
alert(e.target.value);
}
return(
<div className="container-fluid">
<h2>Register User</h2>
<Formik
initialValues={
{
UserName:"",
Age:0,
Mobile:""
}
}
validationSchema={
yup.object({
UserName: yup.string()
.required("User Name Required")
.min(4, "Name too short min 4 chars")
.max(10, "Name too long max 10 chars"),
Age: yup.number()
.required("Age Required"),
Mobile: yup.string()
.required("Mobile Required")
.matches(/\+91\d{10}/, "Invalid Mobile +91 and 10 digits")
})
}
onSubmit= {
(values)=> {
alert(JSON.stringify(values));
}
}
>
{
props =>
<Form className={(props.isValid)?'bg-success':'bg-danger'}>
<dl>
<dt>User Name</dt>
<dd>
<Field name="UserName" type="text"/>
</dd>
<dd className="text-danger" >
<ErrorMessage name="UserName"/>
</dd>
<dt>Age</dt>
<dd>
<Field type="text" name="Age" />
</dd>
<dd className="text-danger" >
<ErrorMessage name="Age" />
</dd>
<dt>Mobile</dt>
<dd>
<Field name="Mobile" type="text" />
</dd>
<dd className="text-danger">
<ErrorMessage name="Mobile" />
</dd>
<dt>City</dt>
<dd>
<Field as="select" onChange={CityChange}>
<option>Delhi</option>
<option>Hyd</option>
</Field>
</dd>
</dl>
<button disabled={!props.isValid} >Register</button>
<button disabled={!props.dirty}>Save</button>
</Form>
}
</Formik>
</div>
)
}
Routing in React
-Every web application comprises of various techniques.
a) Data Binding
b) Model Binding
c) Event Binding
d) Style Binding
e) Class Binding
f) Caching
g) Routing
h) State Management etc..

- Routing is technique used in web applications to create or configure user friendly and SEO friendly
URL's.

Without Routing:
http://www.amazon.in/electronics.php?category=mobiles&brand=realme

Routing
http://www.amazon.in/electronics/mobiles/realme

- Routing is configure both server side and client side.


- Routing implictly enables navigation for SPA.
- User can stay on one page and access everything on to the page.
- Routing implicitly uses Ajax.
- Without reloading the complete page new details are added to page.
- React provides routing library which is not as a part of react core library

React Version 18 React Routing V6


React Version upto 17 Routing V5

Note: React 18 is backward compatible

React Router DOM V6


--------------------------------
1. Install react-router-dom library into project

>npm install react-router-dom --save -D [latest stable]


>npm install react-router-dom@latest [latest not stable]
>npm install react-router-dom@v5 [version 5]

2. React router is not understandable to browser you need a "BrowserRouter" in react, which translates
the navigation mechanism of virtual DOM into actual DOM

import {BrowserRouter} from "react-router-dom";

3. Complete routing configuration must be with in BrowserRouter


<BrowserRouter>

............routing configuraiton...........

</BrowserRouter>

4. RouteTable is created for application by using "<Routes>", It is a collection of routes.

<Routes>
....your routes....
</Routes>

5. Every route is defined by using "<Route>" component.

6. Each route defines details about path and content to render.

<Route path="" element=""> </Route>

Syntax:
<BrowserRouter>
<Routes>
<Route path element> </Route>
<Route path element> </Route>
</Routes>
</BrowserRouter>

7. Routes are requested in browser from URL

http://localhost:3000/home

8. You can use <Link> component which can set path into URL

<Link to="home"> </Link> Relative Link


<Link to="/home"> </Link> Absolute Link

- Relative link will add the current path to the existing path.
- Absolute link sets a new path.

Ex: Basic Route requested from URL

tutorial.component.js

import { BrowserRouter, Routes, Route } from "react-router-dom";

export function TutorialComponent()


{
return(
<div className="container-fluid">
<h2>Tutorial - Web Technologies</h2>
<BrowserRouter>
<Routes>
<Route path="html" element={<div><h3>HTML</h3><p>It is a markup language.</p></div>}
></Route>
<Route path="css" element={<div><h3>CSS</h3><p>It defines styles for
HTML.</p></div>}></Route>
</Routes>
</BrowserRouter>
</div>
)
}

Note: If client requests any component which is not in the route table, then you can render alternative
using wild card routes.

<Route path="/"> What to render when user is not requesting


any specific path.

<Route path="*"> What to render when the requested path is


not found.

Ex: Route requested from Link

import { BrowserRouter, Routes, Route, Link } from "react-router-dom";

export function TutorialComponent()


{
return(
<div className="container-fluid">
<h2>Tutorial - Web Technologies</h2>
<BrowserRouter>
<section className="row">
<nav className="col-3">
<div className="btn-group-vertical">
<Link to="html"> HTML </Link>
<Link to="css">CSS</Link>
</div>
</nav>
<div className="col-9">
<Routes>
<Route path="html" element={<div><h3>HTML</h3><p>It is a markup language.</p></div>}
></Route>
<Route path="css" element={<div><h3>CSS</h3><p>It defines styles for
HTML.</p></div>}></Route>
</Routes>
</div>
</section>

</BrowserRouter>
</div>
)
}

Ex: Links

import { BrowserRouter, Routes, Route, Link } from "react-router-dom";

export function TutorialComponent()


{
return(
<div className="container-fluid">
<h2>Tutorial - Web Technologies</h2>
<BrowserRouter>
<section className="row">
<nav className="col-3">
<div className="btn-group-vertical">
<Link to="html"> HTML </Link>
<Link to="css">CSS</Link>
</div>
</nav>
<div className="col-9">
<Routes>
<Route path="/" element={<p>Online Tutorial Home for HTML and CSS</p>}></Route>
<Route path="html" element={<div><h3>HTML</h3><p>It is a markup language.</p></div>}
></Route>
<Route path="css" element={<div><h3>CSS</h3><p>It defines styles for
HTML.</p></div>}></Route>
<Route path="*" element={<code>404 : Page you requested not found</code>}></Route>
</Routes>
</div>
</section>

</BrowserRouter>
</div>
)
}

Note: Every route path can render element, which can be markup or a component that have markup.

Ex:
import { BrowserRouter, Routes, Route, Link } from "react-router-dom";
import { LoginComponent } from "../login/login.component";
import { RegisterComponent } from "../register/register.component";

export function TutorialComponent()


{
return(
<div className="container-fluid">
<h2>Shopping Home</h2>
<BrowserRouter>
<section className="row">
<nav className="col-3">
<div className="btn-group-vertical">
<Link to="login" className="btn btn-primary mb-2"> Login </Link>
<Link to="register" className="btn btn-primary">Register</Link>
</div>
</nav>
<div className="col-9">
<Routes>
<Route path="/" element={<h2>Shopping Home Page</h2>} />
<Route path="login" element={<LoginComponent/>} />
<Route path="register" element={<RegisterComponent />} />
</Routes>
</div>
</section>

</BrowserRouter>
</div>
)
}

React Shopper Template - SPA

1. Create a new project

> npx create-react-app shopper-template-react

2. Install the packages

> npm install bootstrap --save


> npm install bootstrap-icons --save
> npm install axios --save
> npm install formik --save
> npm install yup --save
> npm install jquery --save
> npm install react-router-dom --save

Route Parameters
<Route path="category/:catname" element={ } />
<Link to="category/name"> </Link>

useParams Hook

You might also like