0% found this document useful (0 votes)
8 views70 pages

React Js

Uploaded by

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

React Js

Uploaded by

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

*DOM:

Document Object Model


=> it represents HTML components as a hierarchy
=> To provide dynamic functionality HTML elements

*Rules for creating web pages using DOM:


=> DOM elements are case sensitive
=> Every DOM elements must be closed.

*Accessing DOM elements:


=> document.getElementById()
<tag id=""></tag>
=> document.getElementByName()
<tag name=""></tag>
=> document.getElementsByClassName()
<tag class=""></tag>
=> document.getElementByTagName()
<tag></tag>
----------------------------------------
<!-- Implementing DOM -->
<html>
<head>
<title>DOM</title>
<script>
function changeHeading()
{
document.getElementById('heading').innerHTML = "Welcome to DOM"
}
</script>
</head>
<body onload="changeHeading()">
<img src="bg2.jpeg" width="100%" height="225" onmouseover="this.src='bg3.jpeg'"
onmouseout="this.src='bg2.jpeg'"> <br></br>
<marquee bgcolor="wheat" onmouseover="this.stop()" onmouseout="this.start()">This
is a Scrolling text</marquee>
<h1 id="heading" align="center"> welcome to JS </h1>
<h1 align="center" onmouseover="innerHTML='Mouse Entered onto this Heading'"
onmouseout="innerHTML='Mouse Exited from this Heading'">Move mouse over this
Heading</h1>
<h1 align="center" onmouseover="this.style.color='red'"
onmouseout="this.style.color='blue'">Move mouse over this heading</h1>
</body>
</html>
-----------------------------------------
<!-- Digital Clock -->
<html>
<head>
<title>Digital clock</title>
<script>
i = 0
function showTime()
{
i = (i+1) % 10
colors =
['red','blue','green','yellow','magenta','cyan','brown','powderblue','pink','orange'
]
today = new Date()
h = today.getHours()
if(h<12)
am_pm = 'AM'
else
{
h = h - 12
am_pm = 'PM'
}
m = today.getMinutes()
s = today.getSeconds()
if(h<10)
h = "0" + h
if(m<10)
m = "0" + m
if(s<10)
s = "0" + s
time = h + ":" + m + ":" + s + am_pm;
document.getElementById('clock').innerHTML = time;
document.getElementById('clock').style.color = colors[i];
setTimeout(showTime,1000);
}
</script>
</head>
<body onload="showTime()">
<h1 align="center" id="clock"></h1>
</body>
</html>
-----------------end-----------------------19th-april-2023 -----end ---------------
<!-- Implementing DOM -->
<html>
<head>
<title>DOM</title>
</head>
<body>
<img id="image" src="images/1.jpg" width="100%" height="225">
<h3>
Select Your Banner Image:
<select onchange="document.getElementById('image').src=this.value">
<option value="images/1.jpg">Image-1</option>
<option value="images/2.jpg">Image-2</option>
<option value="images/3.jpg">Image-3</option>
<option value="images/4.jpg">Image-4</option>
</select> <br><br>
Select Your Favourite Background Color:
<input type="color" onchange="document.body.style.background=this.value"> <br><br>
Select Your Text Color:
<input type="color" onchange="document.body.style.color=this.value"> <br><br>
Enter FirstName:
<input type="text" onfocus="style.background='silver'"
onblur="style.background='wheat'"> <br><br>
Enter LastName:
<input type="text" onfocus="style.background='silver'"
onblur="style.background='wheat'"> <br><br>
Enter password:
<input type="password"
onkeyup="document.getElementById('pwd').innerHTML=this.value"> <br><br>
Your Password:
<span id="pwd"></span>
</h3>
<h1 id="heading">This is a Heading</h1>
<button onclick="document.getElementById('heading').style.visibility='hidden'">Hide
Heading</button>
<button onclick="document.getElementById('heading').style.visibility='visible'">Show
Heading</button>
</body>
</html>
------------------------------------------------------------------
* Local Storage and Session Storage Object:
=> data sharing between web resourses

LocalStorage Object:
=> storing data into localStorage object:
localStorage.setItem(name,value);
=> retrieving data from the localStorage object:
localStorage.getItem(name);
=> deleting the data from the localStorage object:
localStorage.removeItem(name);

Create the following resourses:


1.

<!-- Save this file as setItem.html -->


<h3><script>
localStorage.setItem('userName','APEC');
localStorage.setItem('password','DataDot');
</script></h3>
Your Data Has been Set <br>
<a href="getItem.html">Click Here to see Your Data<a>

2.

<!-- Save this file as getItem.html -->


<h3><script>
document.write("User Name : " + localStorage.getItem('userName'))
document.write("<br>Password : " + localStorage.getItem('password'))
</script></h3>

=> save and load setItem.html

--------------------------------------------------------------------------
SessionStorage object:
=> storing data into sessionStorage object:
sessionStorage.setItem(name,value);
=> retrieving data from the sessionStorage object:
sessionStorage.getItem(name);
=> deleting the data from the sessionStorage object:
sessionStorage.removeItem(name);

1.
<!-- Save this file as setItem.html -->
<h3><script>
sessionStorage.setItem('userName','APEC');
sessionStorage.setItem('password','DataDot');
</script></h3>
Your Data Has been Set <br>
<a href="getItem.html">Click Here to see Your Data<a>

2.
<!-- Save this file as getItem.html -->
<h3><script>
document.write("User Name : " + sessionStorage.getItem('userName'))
document.write("<br>Password : " + sessionStorage.getItem('password'))
</script></h3>

=> save and load setItem.html


---------------------------------------------------------------------------
* page redirecting (or) request dispatching (or) control sharing:
=> passing the control from one web page to another web page.

=> modify setItem.html as below:

<!-- Save this file as setItem.html -->


<h3><script>
sessionStorage.setItem('userName','APEC');
sessionStorage.setItem('password','DataDot');
window.location='getItem.html'
</script></h3>

=> save and run


----------20th april 2023---------------end------------20th april 2023-----
Installing the required Softwateres:
1.Node.js
connect to https://nodejs.org/en/download
download and install it
2.VS code
connect to https://code.visualstudio.com/download#
download and install it
--------------------------------------------------------
* open VS code and navigate to your working directory:
1.create a new JS file as below:

// This is sample program


console.log("Welocme to JS programming")

In order to run the above file


=> open terminal (ctrl+backtick(`))
node filename
eg:
node sample.js (or) node sample

// This is sample program


var a = 100
function welcome()
{
console.log("Welcome to JS")
}
welcome()
console.log("Value of a = " +a)

--------------------------------------
/* Limitation of var keyword */
var a = 100 // global variable
console.log("value of a = " + a)
if(true){
var a = 12.25; // local variable
console.log("value of a = " + a)
}
console.log("value of a = " + a)
----------------------------------------
* solution : let keword

/* Limitation of var keyword */


let a = 100 // global variable
console.log("value of a = " + a)
if(true){
let a = 12.25; // local variable
console.log("value of a = " + a)
}
console.log("value of a = " + a)

--------------------------------------------
* ES6 has provide let and const ketowrd
--------------------------------------------
* functions in JS:

/* Implementing normal functions */


function welcome()
{
console.log("Inside function welcome")
}
function add(x,y)
{
return x+y;
}
welcome();
console.log("Sum of 10,20 : ",add(10,20))

----------------------------------------------
/* Implementing function expressions */
let fun1 = function welcome()
{
console.log("Inside function welcome")
}
let fun2 = function add(x,y)
{
return x+y;
}
fun1();
console.log("Sum of 10,20 : ",fun2(10,20))
------------------------------------------------
/* Implementing Anonymous functions */
let fun1 = function ()
{
console.log("Inside function welcome")
}
let fun2 = function (x,y)
{
return x+y;
}
fun1();
console.log("Sum of 10,20 : ",fun2(10,20))
-----------------------------------------------
/* Implementing Arrow(Fat Arrow) functions */
let fun1 = () =>
{
console.log("Inside function welcome")
}
let fun2 = (x,y) =>
{
return x+y;
}
fun1();
console.log("Sum of 10,20 : ",fun2(10,20))
-----------------------------------------------
/* Implementing lamda functions */
let fun1 = () => console.log("Inside function welcome")

let fun2 = (x,y) => x+y;

fun1();
console.log("Sum of 10,20 : ",fun2(10,20))
-------------------------------------------------
// Accessing the Array Elements
let a = [10,20,30,40,50];
console.log("The Array Elements are : " +a)
console.log("The Array Elements using for loop : ");
for(i=0;i<a.length;i++) // i holds the index values
{
console.log(a[i])
}
console.log("The Array Elements using for in loop : ")
for(i in a) // i holds the index values
{
console.log(a[i])
}
console.log("The Array Elements using for of loop : ")
for(i of a) // i holds the array values
{
console.log(i)
}
console.log("The Array Elements using forEach loop : ")
a.forEach(i => {
console.log(i)
})
------------------24th april 2023------------------------
// Implementing function constructor
let add = Function("x","y","return x+y")
console.log("Sum of 10,20 : " + add(10,20))
---------------------------------------------
// Implementing function constructor
let add = Function("x,y","return x+y")
console.log("Sum of 10,20 : " + add(10,20))
----------------------------------------------
// Implementing default parameters
function add(x=100,y=200)
{
console.log("x value : "+x)
console.log("y value : "+y)
console.log("Sum = ",x+y)
}
add(10,20)
add(10)
add()
------------------------------------------------
// Implementing spread parameters
function add(...x)
{
sum = 0
for(let value of x)
sum += value
console.log("sum = "+sum)
}
add(10,20)
add(10,20,30,40,50)
add(10,20,30,40,50,60,70,80,90,100)
add(12.25,22.5)
add(10)
add()
-----------------------------------------------------
// Implementing Rest parameters
function add(a,b,...x)
{
sum = a+b
for(let value of x)
sum += value
console.log("sum = "+sum)
}
add(10,20)
add(10,20,30,40,50)
add(10,20,30,40,50,60,70,80,90,100)
add(12.25,22.5)
add(10)
add()

-------------------------------------------------------
* Obects in JS:
syntax:
let obj-name = {
propery:value,
propery:value,
propery:value,
....
methods(parameters, if any){
}
}

/* Implementing objects */
let Employee = {
empId : 101,
empName : 'suresh',
salary : 25000
};
console.log(Employee)
console.log("The Emplyee Details are : ");
console.log(Employee.empId + " " + Employee.empName + " " + Employee.salary)
------------------------------------------------
/* Implementing objects */
let Emp1 = {
empId : 101,
empName : 'suresh',
salary : 25000
};
let Emp2 = {
empId : 102,
empName : 'Ramesh',
salary : 26000
};
let Emp3 = {
empId : 103,
empName : 'Naresh',
salary : 27000
};
console.log("The Employee Deatails are : ");
console.log(Emp1.empId + " " + Emp1.empName + " " + Emp1.salary)
console.log(Emp2.empId + " " + Emp2.empName + " " + Emp2.salary)
console.log(Emp3.empId + " " + Emp3.empName + " " + Emp3.salary)
--------------------------------------------------------------
/* Implementing objects */
let Employees = [
{empId:101,empName:'suresh',salary:25000},
{empId:102,empName:'Ramesh',salary:26000},
{empId:103,empName:'Naresh',salary:27000},
{empId:104,empName:'Mahesh',salary:28000},
{empId:105,empName:'Lokesh',salary:29000},
]
console.log("The Employee Details are : ");
for(emp of Employees)
console.log(emp.empId + " " + emp.empName + " " + emp.salary)
---------------------------------------------------------------------
* Object Oriented Programming(OOP) :

1.Encapsulaton: Binding the data with related functions


Data Abstaraction(Information hiding): data will not be available to the outer
functions
class: It is user defined data type through which we implement encapsulation. It
is the combinations variables(data members) and functions (member functions or
methods)
Object: It is the instance variable of the class

2.Polymorphism:(Taking more than one form)


static polymorphism : It is implemented through method overloading
compile time polymorphism: It is implemented through method overriding

3.Inheritance:
A class getting the properties of another class. A class gets the properties of
another class with "extends" keyword. With extends keyword a class can get the
properties of only class. Hence JS does not support multiple inheritance.
syntax:
class A
{
properties;
methods;
}
class B extends A
{
}
---------------25th april
2023--------------------------------------------------------
* Declaring class in JS:
syntax:
class class-name
{
data mebers
member function
}

=> In order to access the class members, we have to create an instance variable, i,e
object as below:

let obj-name = new class-name()

=> with the help of the object, we can access the data members using the dot(.)
operator.

obj-name.datamember;

// creating class and object in a program


class Employee
{
empId=101;
empName='suresh';
salary=25000;
getEmp()
{
console.log(this.empId + " " + this.empName + " " + this.salary )
}
}
let emp = new Employee()
emp.getEmp()
----------------------------------------
// creating class and object in a program
class Employee
{
empId;
empName;
salary;
setEmp(x,y,z){
this.empId = x;
this.empName = y;
this.salary = z;
}
getEmp()
{
console.log(this.empId + " " + this.empName + " " + this.salary )
}
}
let emp1 = new Employee()
let emp2 = new Employee()
let emp3 = new Employee()
emp1.setEmp(101,'suresh',25000)
emp2.setEmp(102,'Ramesh',26000)
emp3.setEmp(103,'Naresh',27000)
emp1.getEmp()
emp2.getEmp()
emp3.getEmp()
-------------------------------------------
// creating a multiple functions in a program
class Sample
{
a;
b;
add(){
this.a = 100;
this.b = 200;
console.log("Sum = " + (this.a + this.b))
}
sub(){
console.log("Difference = " + (this.a - this.b))
}
prod(){
console.log("product = " + (this.a * this.b))
}
div(){
console.log("division = " + (this.a / this.b))
}
}
let s = new Sample()
s.add()
s.sub()
s.prod()
s.div()
---------------------------------------------------
* constructors:
It is a special member function, it will run automatically, it is used to initialize
the data members.

syntax:
constuctor(){

// creating a multiple functions in a program


class Sample
{
a;
b;
constructor()
{
console.log("Inside constructor Sample")
this.a = 100;
this.b = 50;
}
add(){
console.log("Sum = " + (this.a + this.b))
}
sub(){
console.log("Difference = " + (this.a - this.b))
}
prod(){
console.log("product = " + (this.a * this.b))
}
div(){
console.log("division = " + (this.a / this.b))
}
}
let s = new Sample()
s.sub()
s.prod()
s.div()
s.add()
-----------------------------------------------------
/* Implementing non-parameterized constructor */
class Account
{
accId;
balance;
constructor(){
console.log("Inside constructor Account")
this.accId = 201;
this.balance = 25000;
}
showBalance(){
console.log("Balance in " + this.accId + " is " + this.balance)
}
}
let a1 = new Account();
let a2 = new Account();
let a3 = new Account();
a1.showBalance();
a2.showBalance();
a3.showBalance();
-------------------------------------------
/* Implementing parameterized constructor */
class Account
{
accId;
balance;
constructor(x,y){
console.log("Inside constructor Account")
this.accId = x;
this.balance = y;
}
showBalance(){
console.log("Balance in " + this.accId + " is " + this.balance)
}
}
let a1 = new Account(201,25000);
let a2 = new Account(202,26000);
let a3 = new Account(203,27000);
a1.showBalance();
a2.showBalance();
a3.showBalance();
--------------------------------------------
* Inheritance : A class getting the properties of another class
A class can get the properties of another class with the help of "extends" keyword.
A class can extend only one class, hence JS does not support multiple inheritance.
syntax:
class A
{
data members
member functions
}
class B extends A
{
}

// Implementing single inheritance


class Square
{
l;
constructor(){
console .log("Inside constructor Square")
this.l = 10;
}
area1(){
console.log("Area of Square : " + (this.l * this.l))
}
}
class Rectangle extends Square
{
b;
constructor(){
super()
console.log("Inside constructor Rectangle")
this.b = 20;
}
area2(){
console.log("Area of Reactangle : " + (this.l * this.b))
}
}
let r = new Rectangle()
r.area1();
r.area2();
---------------------------------------
NOTE: In any type of inheritance the child class object will get only after its
parent class objects.
-------------------26th april 2023-----------------------------------------------
// muliti level inheritance
class Square
{
l;
constructor(){
this.l = 10;
}
area1(){
console.log("Area of Square : " + (this.l*this.l))
}
}
class Rectangle extends Square
{
b;
constructor(){
super();
this.b = 20;
}
area2(){
console.log("Area of Rectangle : " +(this.l*this.b))
}
}
class Cube extends Rectangle
{
h;
constructor(){
super();
this.h = 30;
}
area3(){
console.log("Volume of Cube : " + (this.l * this.b * this.h))
}
}
let c = new Cube()
c.area1()
c.area2()
c.area3()

---------------------------------
* Method overriding:
A sub-class defining its own functionality for the member of its super class is
called method overriding. A sub class along with its methods, can overide its
constructor also.

/* Implementing method overloading */


class Square
{
l;
constructor(){
this.l = 10;
}
area(){
console.log("Area of Square : " + (this.l * this.l))
}
}
class Rectangle extends Square
{
b;
constructor(){
super();
this.l = 15;
this.b = 20;
}
area(){
console.log("Area of Rectangle : " + (this.l * this.b))
}
}
class Cube extends Rectangle
{
h;
constructor(){
super();
this.l = 20;
this.b = 25;
this.h = 30;
}
area(){
console.log("volume of Cube : " + (this.l * this.b * this.h))
}
}
let c = new Cube()
c.area()
--------------------------------------------
* super keyword:
"super" is a keyword in JS that can be used for 2 purposes:
1.To call the super-class members from the sub-class
2.To call the super-class constructor from the sub-class

// Implementing super keyword


class Square
{
l;
constructor(x){
this.l = x;
}
area(){
console.log("Area of Square : " + (this.l*this.l))
}
}
class Rectangle extends Square
{
b;
constructor(x,y)
{
super(x);
this.b = y;
}
area(){
super.area()
console.log("Area of Rectangle : " + (this.l * this.b))
}
}
class Cube extends Rectangle
{
h;
constructor(x,y,z){
super(x,y)
this.h = z;
}
area(){
super.area()
console.log("Volume of Cube : " + (this.l*this.b*this.h))
}
}
let c = new Cube(10,20,30)
c.area()
-----------------------------------
/* Implementing call back functions */
function fun1()
{
console.log("Inside fun1")
}
function fun2()
{
console.log("Inside fun2")
}
function fun3()
{
console.log("Inside fun3")
}
setTimeout(fun1,8000)
setTimeout(fun2,2000)
setTimeout(fun3,4000)
---------------27th april 2023----------------------------------------
What is React?

=> React (also known as React.js or ReactJS) is an open-source, front end,


JavaScript library for building Single-Page Applications. It is maintained by
Facebook and a community of individual developers and companies.

=> React is an open source JavaScript Library for building Rich User Interface. It
is not a framework,just a library

=> React is just used for building rich UI, but not focuses on routing, HTTP
requests etc.
---------------------------------------------
History of React JS:

=> React was created by Jordan Walke, a software engineer at Facebook, who released
an early prototype of React called "FaxJS". He was influenced by XHP, an HTML
component library for PHP. It was first deployed on Facebook's News Feed in 2011 and
later on Instagram in 2012. It was open-sourced at JSConf US in May 2013

=> React Native, which enables native Android, iOS, and UWP development with React,
was announced at Facebook's React Conf in February 2015 and open-sourced in March
2015.

=> On April 18, 2017, Facebook announced React Fiber, a new core algorithm of React
library for building user interfaces. React Fiber was to become the foundation of
any future improvements and feature development of the React library.

=> On September 26, 2017, React 16.0 was released to the public.
=> On February 16, 2019, React 16.8 was released to the public. The release
introduced React Hooks
------------------------------------------------------
Top 10 companies using React JS:
1) Facebook
2) Instagram
3) Netflix
4) New York Times
5) Yahoo mail
6) Khan Academy
7) WhatsApp
8) Codeacademy
9) Vivaldi Browser
10) Dropbox
-------------------------------------------------------
Why React?
=> The first requirement for companies
=> Maintained by Facebook.
=> Has a huge community on GitHub.
=> Has large number of articles on StackOverflow

Technical Reasons:
=> React follows component-based Architecture. A component is an encapsulated part
composed with other components to make complex UI.
=> Components allow users to create reusable code.
=> React is declarative,not imperative
=> Can be easily integrated into any of our application
=> React native will become an addition to our skillset.

Prerequisites :
=> HTML,JS,CSS,Bootstrap
=> ES6 and later concepts
--------------------------------------------------
Creating our first react application:

== Start VS Code and change to your working directory


== Create a new react project as below:
npx create-react-app application-name
Eg:
npx create-react-app sample-app

== Once project is build, change to project folder and run the application as:
npm start

== To terminate the project, type CTRL + C at the terminal


=============================================
Project structure:
1) node_modules(F) : Contains all dependencies(libraries) required for our project
2) public(F) : This folder includes:
== favicon.ico
== index.html : The only html file of our React application
== manifest.json : To create progressive webapps
3) src(F) : Working directory of our React project. This folder includes:
== App.js : Root component of our application
== App.css : styles to be applied for App component
== App.test.js : To write test cases for App component
== index.css : Global styles for the application
== index.js : Entry point of the application
== reportWebVitals.js : To send information about our application
== setuptests.js : To write test cases
4) package.json : Contains the dependencies and the environment about our
application
==============================================
Modifying the existing application:
=>Modify the App.js

function App() {
return (
<div>
<h1 align='center'>Welcome to React</h1>
</div>
);
}

export default App;


--------------------------------------
function App() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit <code>src/App.js</code> and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
</header>
</div>
);
}
--------------------------28th april 2023-------------------------------------
Modify the project as below:
=> Modify package.json file:
....
"dependencies": {
"@testing-library/jest-dom": "^5.16.5",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
},
...
=============================================
=> Modify index.js file:

import React from 'react';


import ReactDOM from 'react-dom';
import './index.css';
import App from './App';

ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);

=> save and run


=============================================
Rules for writing HTML code in React JS:

1) All the HTML(DOM) elements must have a root element


2) DOM elements are case sensitive. Better write the DOM elements in lowercase
3) Every DOM element must be closed.
4) Attribute values must be quoted.
---------------------------------------------
=> Modify App.js as below:

// IMplementing App component as a normal function


import './App.css';

function App() {
return (
<div>
<h3 align='center'>IMplementing App component as normal function</h3>
</div>
);
}

export default App;


=> save and run
------------------------------------------
// IMplementing App component as Anonymous function
import './App.css';

const App = function () {


return (
<div>
<h3 align='center'>Implementing App component as Anonymous function</h3>
</div>
);
}

export default App;

=> save and run


--------------------------------------------
// IMplementing App component as Arrow function
import './App.css';

const App = () => {


return (
<div>
<h3 align='center'>Implementing App component as Arrow function</h3>
</div>
);
}

export default App;

=> save and run


=============================================
// IMplementing App component as a lamda function
import './App.css';

const App = () =>


<div>
<h3 align='center'>Implementing App component as lamda function</h3>
</div>
export default App;

=> save and run


-------------------------------------------
Components in React JS:
=> React follows component-based development approach. Components are part of UI
=> Components provide code reusability
=> A component can be either a header, or a sidenav or a footer...
=> The root component of a React Application is "App" Component. All components are
declared as child components to this
=> The component code must be placed in a JS file(with ".js" or ".jsx" extension)
-------------------------------------------
Types of components:
=> React JS supports 2 types of components : Stateless functional components and
Stateful class components

1) Stateless functional components:


=> They are JS functions
=> These functions take an object as parameter,called "props" and returns the HTML
code to be rendered onto the page

=> Working with VS Code snippets


---------------------------------------------
* Create a folder named "components" inside "src" folder
=> Inside "components" folder create a functional component named "FunComp.js" as
below(rsf):

import React from 'react';

function FunComp(props) {
return (
<div>
<h3 align='center'>Inside FunComp</h3>
</div>
);
}

export default FunComp;

=> Add this FunComp.js inside App.js as below:

// IMplementing App component as a lamda function


import './App.css';
import FunComp from './components/FunComp';

const App = () =>


<div>
<h3 align='center'>Inside App</h3>
<FunComp/>
</div>
export default App;

=> save and run


-----------------29th april 2023--------------------------------------
// Implementing FunComp.js as anonymous function
import React from 'react';

const FunComp = function (props) {


return (
<div>
<h3 align='center'>
Implementing FunComp as anonymous function
</h3>
</div>
);
}

export default FunComp;


------------------------------------------------------
// Implementing FunComp.js as Arrow function
import React from 'react';

const FunComp = (props) => {


return (
<div>
<h3 align='center'>
Implementing FunComp as an Arrow function
</h3>
</div>
);
}

export default FunComp;


-------------------------------------------------------
// Implementing FunComp.js as lamda function
import React from 'react';

const FunComp = (props) =>

<div>
<h3 align='center'>
Implementing FunComp as lamda function
</h3>
</div>

export default FunComp;


-------------------------------------------------------
* passing props as parameter to a functional component:

=> modify App.js

import './App.css';
import FunComp from './components/FunComp';

function App() {
return (
<div>
<FunComp name="APEC" location="Ameerpet"/>
<FunComp name="Datadot" location="Begumpet"/>
</div>
);
}

export default App;

=> modify FunComp.js

import React from 'react';

function FunComp(props) {
return (
<div>
<h3 align='center'>
{props.name} is located at {props.location}
</h3>
</div>
);
}

export default FunComp;

=> Save and run


-------------------------------------------------
* passing different types of props to a functional components:

=> modify App.js as below:

import './App.css';
import FunComp from './components/FunComp';

function App() {
return (
<div>
<FunComp name='suresh' subject='Java'/>
<FunComp name='Ramesh' subject='Python'/>
<FunComp name='Naresh' subject='HTML'/>
</div>
);
}

export default App;

=> modify FunComp.js

import React from 'react';

function FunComp(props) {
return (
<div>
<h3 align='center'>
{props.name} is the faculty of {props.subject}
</h3>
</div>
);
}

export default FunComp;


----------------------------------------
* "props" are immutable i.e they cannot be updated. for Eg: the following code does
not work:

=> modify App.js

import './App.css';
import FunComp from './components/FunComp';

function App() {
return (
<div>
<FunComp name='suresh' subject='Java'/>
</div>
);
}

export default App;

=> modify FunComp.js

import React from 'react';

function FunComp(props) {
props.name = 'Ramesh';
return (
<div>
<h3 align='center'>
{props.name} is the faculty of {props.subject}
</h3>
</div>
);
}

export default FunComp;

=> save and run


----------------------------------------
* Working with class components(rcc):
=> create a file named "ClassComp.js" inside "components" folder as below:

import React, { Component } from 'react';


class ClassComp extends Component {
render() {
return (
<div>
<h3 align='center'>
This is a class Component
</h3>
</div>
);
}
}

export default ClassComp;

=> Add this ClassComp.js inside App.js as below:

import './App.css';

import ClassComp from './components/ClassComp';

const App = () =>


<div>
<ClassComp/>
</div>
export default App;

=> Save and run


--------------------------------------------------------
* passing props as parameters to a class component:

=> modify App.js as below:

import './App.css';

import ClassComp from './components/ClassComp';

const App = () =>


<div>
<ClassComp name="APEC" location="Ameerpet"/>
<ClassComp name="Datadot" location="Begumpet"/>
<ClassComp name="Siritech" location="Nellore"/>
</div>
export default App;

=> ClassComp.js

import React, { Component } from 'react';

class ClassComp extends Component {


render() {
return (
<div>
<h3 align='center'>
{this.props.name} is located at {this.props.location}
</h3>
</div>
);
}
}

export default ClassComp;

=> save and run


-----------------------------------------------------
* Which component when?
1)Functional component:
= use as many as possible. If you have given a choice of selecting either of class
component or functional component, prefer functioal component.
Reasons:
1.Absence of "this" keyword
2.creating a solution without having a state. It multiple components have their own
state, maintaining and debugging will be complex.
3.They provide simple logic and hence the functoional components are also called as
stateless/dumb/presentational components.

2.Class Components:
= Has rich features
= can have their own private data called "state"
= it can maintain complex UI logic
= Because of their use, they are also called as stateful/smart/container components.

---------------------------------------------------------
* Component state in React :
=> A state is the second way of rendering the data onto the screen.
=> A state is an object that is privately maintained by a class component. It
influences what is to be rendered on the browser.

=> modify App.js as below:

import './App.css';

import ClassComp from './components/ClassComp';

const App = () =>


<div>
<ClassComp/>
</div>
export default App;
=> modify ClassComp.js as below:

import React, { Component } from 'react';

class ClassComp extends Component {


constructor(){
super()
this.state = {
name : 'APEC',
location : 'Ameerpet'
}
}
render() {
return (
<div>
<h3 align='center'>
{this.state.name} is located at {this.state.location}
</h3>
</div>
);
}
}

export default ClassComp;

=> save and run


--------------------------------------------
* modifying the state dynamically:

=> modify ClassComp.js as below:

import React, { Component } from 'react';

class ClassComp extends Component {


constructor(){
super()
this.state = {
name : 'APEC',
location : 'Ameerpet'
}
}
changeState = () => {
this.setState({
name : 'Datadot',
location : 'Begumpet'
})
}
render() {
return (
<div>
<h3 align='center'>
{this.state.name} is located at {this.state.location} <br/>
<button onClick={this.changeState}>Update State Data</button>

</h3>
</div>
);
}
}

export default ClassComp;


---------------------------------------------------
* Updating the state Dynamically:

=> modify ClassComp.js

import React, { Component } from 'react';

class ClassComp extends Component {


constructor(){
super()
this.state = {
name : 'APEC',
location : 'Ameerpet'
}
}
render() {
return (
<div>
<h3 align='center'>
{this.state.name} is located at {this.state.location} <br/>
<button onClick={() =>
this.setState({name:'Datadot',location:'Begumpet'})}>Update State Data</button>

</h3>
</div>
);
}
}

export default ClassComp;


----------------------1st may---------------------------------------
* Objects:
== properties(data)
== behavior(methods)

Account:
== properties(data) : accid,balance,
== methods : create(), update(), delete(),...
Employee:
== properties : empid,empName,salary,phno,address,....
== methods : create(), update(), delete(), print(),...

-------------------------------------------------------
<!-- Implementing Date object -->
<h3><script>
var today = new Date();
document.write("Today is : " + today)
var d = today.getDay()
switch(d)
{
case 0 : document.write("<br>Today is Sunday");
break;
case 1 : document.write("<br>Today is Monday");
break;
case 2 : document.write("<br>Today is Tuesday");
break;
case 3 : document.write("<br>Today is Wednesday");
break;
case 4 : document.write("<br>Today is Thursday");
break;
case 5 : document.write("<br>Today is Friday");
break;
case 6 : document.write("<br>Today is Saturday");
break;
}
</script></h3>
----------------------------------------------------------
<!-- Implementing Date object -->
<h3><script>
var today = new Date();
document.write("Today is : " + today)
document.write("<br>Current Time is => " + today.getHours() + ":" +
today.getMinutes() + ":" + today.getSeconds())
document.write("<br>Today's Date is : " + today.getDate() + "/" +
(today.getMonth()+1) + "/" + today.getFullYear())

switch(today.getMonth())
{
case 0 : document.write("<br>We are in January"); break;
case 1 : document.write("<br>We are in February"); break;
case 2 : document.write("<br>We are in March"); break;
case 3 : document.write("<br>We are in April"); break;
case 4 : document.write("<br>We are in May"); break;
case 5 : document.write("<br>We are in June"); break;
case 6 : document.write("<br>We are in July"); break;
case 7 : document.write("<br>We are in August"); break;
case 8 : document.write("<br>We are in September"); break;
case 9 : document.write("<br>We are in October"); break;
case 10 : document.write("<br>We are in November"); break;
case 11 : document.write("<br>We are in December"); break;
}
</script></h3>

----------------------------------------------------------------
<!-- Implementing Math object -->
<h3><script>
document.write("Value of PI : " + Math.PI)
document.write("<br>Value of E : " + Math.E)
document.write("<br>Square root of 2 : " + Math.SQRT2)
document.write("<br>Square root of 1/2 : " + Math.SQRT1_2)
document.write("<br>Square root of 0 : " + Math.SQRT0)

document.write("<br>Absolute value of 10 : " + Math.abs(10))


document.write("<br>Absolute value of -10 : " + Math.abs(-10))

document.write("<br>10 power 3 : " + Math.pow(10,3))


document.write("<br>10 power -3 : " + Math.pow(10,-3))
document.write("<br>-10 power 3 : " + Math.pow(-10,3))
document.write("<br>-10 power -3 : " + Math.pow(-10,-3))

document.write("<br>value of sin0 : " + Math.sin(0))


document.write("<br>value of cos0 : " + Math.cos(0))
document.write("<br>value of tan0 : " + Math.tan(0))

document.write("<br>Square root of 10 : " + Math.sqrt(10))


document.write("<br>Square root of -10 : " + Math.sqrt(-10))

document.write("<br>Rounded value of 10.5 : " + Math.round(10.5))


document.write("<br>Next Immediate Integer of 10.1 : " + Math.ceil(10.1))
document.write("<br>Previous Immediate Integer of 10.1 : " + Math.floor(10.1))
document.write("<br>Random value between 0 and 1 : " + Math.random());
</script></h3>
------------------------html 1st may 2023-----------------------
* Working with forms:
=> create a file named "FormComp.js" inside "components" folder. Add the file in the
App component

import React, { Component } from 'react';

class FormComp extends Component {


constructor(){
super()
this.state = {
name : ''
}
}
render() {
return (
<div>
Enter Your Name :
<input onChange={(event) =>
this.setState({name:event.target.value})}/>
<h3>
Welcome {this.state.name}
</h3>
</div>
);
}
}

export default FormComp;

=> Add this component in App.js as below:

import './App.css';
import FormComp from './components/FormComp';

const App = () =>


<div>
<FormComp/>
</div>
export default App;

=> Save and run


--------------------------------------------------------
=> modify FormComp.js as below:

import React, { Component } from 'react';

class FormComp extends Component {


constructor(){
super();
this.state = {
pname : '',
pcost : null,
qty : null,
bill_amt : null
};
}
showBill = () => {
let bill = this.state.pcost * this.state.qty;
this.setState({bill_amt:bill})
}
render() {
return (
<div>
<h3 align='center'>SALES BILL APPLICATION</h3>
<table cellPadding="5" align='center' >
<tr>
<th>Enter Product Name : </th>
<th><input onChange={(event) =>
this.setState({pname:event.target.value})}/></th>
</tr>
<tr>
<th>Enter Product Cost : </th>
<th><input onChange={(event) =>
this.setState({pcost:event.target.value})}/></th>
</tr>
<tr>
<th>Enter Quantity ordered : </th>
<th><input onChange={(event) =>
this.setState({qty:event.target.value})}/></th>
</tr>
<tr>
<th>Bill Amount : </th>
<th><input type="number" value={this.state.bill_amt}
readOnly/></th>
</tr>
<tr>
<th colSpan="2">
<button onClick={this.showBill}>GENERATE BILL</button>
</th>
</tr>
</table>
</div>
);
}
}

export default FormComp;


----------------------------------------------
=> modify FunComp.js as below:

import React, { Component } from 'react';

class FormComp extends Component {


constructor(){
super();
this.state = {
pres : null,
prev : null,
no_units : null,
unit_price : null,
bill_amt : null
};
}
showBill = () => {
let units,price,bill;
units = this.state.pres - this.state.prev
if(units < 100)
price = 2.15
else if(units < 200)
price = 2.65
else
price = 3.15
bill = units * price;
this.setState({
no_units : units,
unit_price : price,
bill_amt : bill
});
}
render() {
return (
<div>
<h3 align='center'>ELECTRICITY BILL APPLICATION</h3>

<table cellPadding="5" align='center' >


<tr>
<th>Enter Present Reading : </th>
<th><input onChange={(event) =>
this.setState({pres:event.target.value})}/></th>
</tr>
<tr>
<th>Enter Previsou Reading : </th>
<th><input onChange={(event) =>
this.setState({prev:event.target.value})}/></th>
</tr>
<tr>
<th>No of Units consumed : </th>
<th><input type="number" value={this.state.no_units}
readOnly/></th>
</tr>
<tr>
<th>Unit price : </th>
<th><input type="number" value={this.state.unit_price}
readOnly/></th>
</tr>
<tr>
<th>Bill Amount : </th>
<th><input type="number" value={this.state.bill_amt}
readOnly/></th>
</tr>
<tr>
<th colSpan="2">
<button onClick={this.showBill}>GENERATE BILL</button>
</th>
</tr>
</table>
</div>
);
}
}

export default FormComp;


-------------------------------------------------------------------
* styles in JS:

1. Inline styles
2. CSS stylesheet
3. CSS modules

1.Inline styles: Here, the styles are specified as JS objects in camelCase

Eg:
=> create a file named "Inline.js" inside "components" folder and add that component
in the App.js as below:

import React from 'react';

function Inline(props) {
return (
<div>
<h3
style={{textAlign:'center',color:'red',backgroundColor:'black',fontFamily:'Monotype
Corsiva'}}>welcome to CSS</h3>
<h3
style={{textAlign:'center',color:'blue',backgroundColor:'cyan',fontFamily:'Consolas'
}}>welcome to CSS</h3>
<h3
style={{textAlign:'center',color:'green',backgroundColor:'yellow',fontFamily:'SansSe
rif'}}>welcome to CSS</h3>
</div>
);
}

export default Inline;

=> modify App.js

import './App.css';
import Inline from './components/Inline';

const App = () =>


<div>
<Inline/>
</div>
export default App;
---------------------------------------------------
=> modify Inline.js as below:

import React from 'react';

function Inline(props) {
const mystyles = {
textAlign : 'center',
color: 'red',
backgroundColor : 'black',
fontFamily : 'Monotype Corsiva',
fontSize : '50px',
letterSpacing : '10px',
wordSpacing : '15px'
};
return (
<div>
<h3 style={mystyles}>welcome to CSS</h3>
<h3 style={mystyles}>welcome to CSS</h3>
<h3 style={mystyles}>welcome to CSS</h3>
</div>
);
}

export default Inline;


--------------------2nd may 2023--------------------------------------------------
2.CSS style sheets: Here, the styles to be applied for several components, they are
dified inside a css file and import into any component in the appliction.
=> create a new file named "mystyles.css" inside "components" folder as below:

.class1{
color:red;
background-color: black;
}
.class2{
color:blue;
background-color: cyan;
}

.class3{
color:green;
background-color: yellow;
}

=> Import the style sheet inside Inline.js as below:

import React from 'react';


import './mystyles.css';
function Inline(props) {
return (
<div>
<h3 className='class1'>Inside Inline component</h3>
<h3 className='class2'>Inside Inline component</h3>
<h3 className='class3'>Inside Inline component</h3>
</div>
);
}

export default Inline;

=> save and run

----------------------------------------------------------
=> import the mystyle.css inside App.js as below:

import './App.css';
import Inline from './components/Inline';
import './components/mystyles.css'

const App = () =>


<div>
<h1 className="class1">Inside App</h1>
<h1 className="class2">Inside App</h1>
<h1 className="class3">Inside App</h1>
<Inline/>
</div>
export default App;

=> save and run


------------------------------------------------------------
=> modify Inline.js as below:

import './App.css';
import Inline from './components/Inline';
import './components/mystyles.css'

const App = () =>


<div>
<h1 className="class1">Inside App</h1>
<h1 className="class2">Inside App</h1>
<h1 className="class3">Inside App</h1>
<Inline/>
</div>
export default App;

=> save and run

--------------------------------------------------------------
* Limitations of CSS stylesheets:
whenever we include a stylesheet in a parent component, it will be automatically
available to all its child components. This may leads to the naming conflicts.

Solution: CSS modules


----------------------------------------------------------------
3. CSS modules:
=> In this type of style sheets the styles that are declared are available only to
the component which imports it, but not its child components. These style sheets
will have the extension "module.css"

eg:
=> create a file named "mystyles.module.css" inside components folder as below:

.class1{
color:red;
background-color: black;
}
.class2{
color:blue;
background-color: cyan;
}

.class3{
color:green;
background-color: yellow;
}

=> Import the file inside App.js as below:

import './App.css';
import Inline from './components/Inline';
import styles from './components/mystyles.module.css'

const App = () =>


<div>
<h1 className={styles.class1}>Inside App</h1>
<h1 className={styles.class2}>Inside App</h1>
<h1 className={styles.class3}>Inside App</h1>
<Inline/>
</div>
export default App;

=> save and run


----------------------------------------------------------
=> Now access the above styles inside Inline.js as below:

import React from 'react';

function Inline(props) {
return (
<div>
<h1 className={styles.class1}>Inside Inline</h1>
<h1 className={styles.class2}>Inside Inline</h1>
<h1 className={styles.class3}>Inside Inline</h1>
</div>
);
}

export default Inline;

=> save and run


=> It will display an error message, "styles" is not defied in "Inline.js". Since
the css modules imported in App.js component, will not be availabe to its child
component.
=> If we want to access the styles from CSS modules, inside Inline.js also, import
inside Inline.js as below

import React from 'react';


import styles from './mystyles.module.css'

function Inline(props) {
return (
<div>
<h1 className={styles.class1}>Inside Inline</h1>
<h1 className={styles.class2}>Inside Inline</h1>
<h1 className={styles.class3}>Inside Inline</h1>
</div>
);
}

export default Inline;

---------------------------------------------------------------------
* Implementing Bootstrap in React:

1. Including the CDN (production mode)


2. Installing using npm (developer mode)

1. Including the CDN :

<link rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css">
<script
src="https://cdn.jsdelivr.net/npm/jquery@3.6.4/dist/jquery.slim.min.js"></script>
<script
src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"></script>
<script
src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js"><
/script>
=> copy the above CDN inside index.html as below:

=> 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" />
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<title>React App</title>
<link rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css">
<script
src="https://cdn.jsdelivr.net/npm/jquery@3.6.4/dist/jquery.slim.min.js"></script>
<script
src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"></script>
<script
src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js"><
/script>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
</body>
</html>

------------------------------------------
=> modify App.js as below:

import './App.css';

function App() {
return (
<div class="container">
<div class="jumbotron">
<h3 align="center">Welcome to Bootstarp in React</h3>
</div>
</div>
);
}
export default App;

--------------------------------------------
2. Installing using npm
=> before installing remove the CDN from index.html

=> install bootstrap using as below:


npm install bootstrap@4.6.2

=> import bootstrap inside index.js as below:

import React from 'react';


import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import 'bootstrap/dist/css/bootstrap.min.css'

ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);

--------------------3rd may 2023--------------------------------------


* working with font-awesome library:

1. Including the CDN (production mode)


2. Installing using npm (developer mode)

1. Including the CDN (production mode)

=> copy and paste the following CDN index.html file as below:

....
<link rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min
.css">
.....

----------------
2. modify App.js

import './App.css';

const App = () =>


<div class="container-flex">
<table class="table table-border table-hover table-dark">
<thead>
<tr>
<th>EMPloyee Name</th>
<th>Designation</th>
<th>Salary</th>
<th>UPdate</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<tr>
<td>Suresh</td>
<td>Admin</td>
<td>25000</td>
<td>
<a href="#"><i class="fa fa-edit"></i></a>
</td>
<td>
<a href="#"><i class="fa fa-trash"></i></a>
</td>
</tr>
<tr>
<td>Rameesh</td>
<td>Faculty</td>
<td>35000</td>
<td>
<a href="#"><i class="fa fa-edit"></i></a>
</td>
<td>
<a href="#"><i class="fa fa-trash"></i></a>
</td>
</tr>
<tr>
<td>Mahesh</td>
<td>Manager</td>
<td>45000</td>
<td>
<a href="#"><i class="fa fa-edit"></i></a>
</td>
<td>
<a href="#"><i class="fa fa-trash"></i></a>
</td>
</tr>
</tbody>
</table>
</div>
export default App;

-----------------------------------------------
2. Installing using npm
=> before installing remove the CDN from index.html
=> install bootstrap using as below:
npm install font-awesome@4.7.0

=> import font-awesome in index.js as below:

import React from 'react';


import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import 'bootstrap/dist/css/bootstrap.min.css';
import 'font-awesome/css/font-awesome.min.css';

ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);

=> save and run


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

* Routing in React :
1) Create a new project as below:
npx create-react-app routing-app

=> package.json:
.....
"dependencies": {
"@testing-library/jest-dom": "^5.16.5",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
},
.....

=> modify index.js:


import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';

ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
--------------------------------------------------------
2) Install react-router-dom as below:
npm install react-router-dom@5.2.0
--------------------------------------------------------
3) Create a folder named "components" inside "src" folder. Create the following
files inside the folder:
== About.js
== Services.js
== ContactUs.js

=> About.js
import React from 'react';

function About(props) {
return (
<div>
<h3 align="center">Inside About</h3>
</div>
);
}

export default About;


-----------------------------------
=> modify Services.js
import React from 'react';

function Services(props) {
return (
<div>
<h3 align="center">Inside Services</h3>
</div>
);
}

export default Services;


-------------------------------------
=> modify ContactUs.js

import React from 'react';

function ContactUs(props) {
return (
<div>
<h3 align="center">Inside ContactUs</h3>
</div>
);
}

export default ContactUs;


---------------------------------------
=> modify App.js as below:

import './App.css';
import About from './components/About';
import Services from './components/Services';
import ContactUs from './components/ContactUs';
function App() {
return (
<div>
<About/>
<Services/>
<ContactUs/>
</div>
);
}

export default App;

------------------------------------------------
=> Apply Routing to the Application :
=> App.js:

import './App.css';
import About from './components/About';
import Services from './components/Services';
import ContactUs from './components/ContactUs';
import {BrowserRouter as Router,Link,Switch,Route} from 'react-router-dom';

function App() {
return (
<div>
<Router>
<nav>
<ul>
<li>
<Link to="/">About</Link>
</li>
<li>
<Link to="/services">Services</Link>
</li>
<li>
<Link to="/contactus">ContactUs</Link>
</li>
</ul>
</nav>

<Switch>
<Route exact path="/"><About/></Route>
<Route path="/services"><Services/></Route>
<Route path="/contactus"><ContactUs/></Route>
</Switch>
</Router>
</div>
);
}

export default App;

=> save and run


-----------------------------
Applying styles to NavBar:
=> modify App.css :

ul{
list-style-type: none;
margin: 0%;
padding: 0%;
overflow: hidden;
background-color: black;
}
li{
float: left;
}
li a{
color : white;
display: block;
padding : 14px 16px;
text-align: center;
text-decoration: none;
}
li a:hover{
background-color: red;
}
-----------------------------------------------
* Hooks in React:
=> Introduced in React 16.8
=> It allows us to create and maintain state in without writing a class
=> works with only functional components, not in class components
eg:

=> create a component named "HooksComp.js" inside "components" folder :

import React, {useState} from 'react';

function HooksComp(props) {
const [ctr,setCtr] = useState(0);
let changeCounter = () => {
setCtr(ctr + 1)
}
return (
<div>
<h3 align="center">
Current Counter Value : {ctr} <br/>
<button onClick={changeCounter}>update counter value</button>
</h3>
</div>
);
}

export default HooksComp;


----------------------4th may 2023----------------------------------
Hooks in React:
=> Introduced in React 16.8
=> It allows us to create and maintain state without writing a class
=> Works in functional components only; not in class components
Eg:
=> Create a component named "HooksComp.js" inside "components" folder as below:

import React, { useState } from 'react';

function HooksComp(props) {
const [ctr,setCtr] = useState(0);
let changeCounter = () => {
setCtr(ctr + 1)
}
return (
<div>
<h3 align='center'>
Current Counter value : {ctr} <br />
<button onClick={changeCounter}>
Increment Counter
</button>
</h3>
</div>
);
}

export default HooksComp;


-----------------------------------
=> Add the component inside App.js
=> Save and run

=> Modify HooksComp.js as below:

import React, { useState } from 'react';

function HooksComp(props) {
const [ctr,setCtr] = useState(0);
return (
<div>
<h3 align='center'>
Current Counter value : {ctr} <br />
<button onClick={() => setCtr(ctr + 1)}>
Increment Counter
</button>
</h3>
</div>
);
}

export default HooksComp;


=> save and run
-----------------------------------
Eg-2: Working with multiple state variables
=> HooksComp.js:

import React, { useState } from 'react';

function HooksComp(props) {
const [ctr1,setCtr1] = useState(0);
const [ctr2,setCtr2] = useState(0);

return (
<div>
<h3 align='center'>
Current Counter-1 value : {ctr1} <br />
<button onClick={() => setCtr1(ctr1 + 1)}>
Increment Counter-1
</button>
</h3>
<h3 align='center'>
Current Counter-2 value : {ctr2} <br />
<button onClick={() => setCtr2(ctr2 - 1)}>
Decrement Counter-2
</button>
</h3>
</div>
);
}

export default HooksComp;

=> save and run


-------------------------------------------------
Eg-3:
=> HooksComp.js:

import React, { useState } from 'react';


function HooksComp(props) {
const [id,setId] = useState(101);
const [name,setName] = useState('Ramesh');
const [salary,setSalary] = useState(40000.00);

const changeEmpData = () => {


setId(102);
setName('Satish');
setSalary(50000.00);
}

return (
<div>
<h3>
The Employee Details are : <br />
Employee ID : {id} <br />
Employee Name : {name} <br />
Basic Salary : {salary} <br />
<button onClick={changeEmpData}>Update Employee Data</button>
</h3>
</div>
);
}

export default HooksComp;

=> save and run


------------------------------------------
Hooks:
== Simple to learn and code
== It allows to break a complex component into smaller functional components
== Hooks are optional
== Hooks are just an alternative for class component but not a replacement
------------------------------------------
useEffect hook :
== This hook allows us to perform side effects in functional components
== The side effects can be fetching data from a data source, subscribing to some
data, changing the DOM manually etc....
Eg:
== HooksComp.js as below:

import React, { useEffect, useState } from 'react';

function HooksComp(props) {
const [ctr,setCtr] = useState(0);
let changeCounter = () => {
setCtr(ctr + 1)
}
useEffect(() => {
document.title = `Current Counter Value : ${ctr}`
})

return (
<div>
<h3 align='center'>
Current Counter value : {ctr} <br />
<button onClick={changeCounter}>
Increment Counter
</button>
</h3>
</div>
);
}

export default HooksComp;

=> save and run


---------------------------------------
Http Requests:
=> get : to fetch(read) data from data source
=> post : to insert data into data source
=> put : to update data in the data source
=> delete : to delete data from data source
---------------------------------------------------
Performing Http request using useEffect hook:

=> To connect to an external data source and perform HTTP requests, we use axios
library in React.
=> Install axios as below:
npm install axios

=> Create a file named "FetchData.js" inside the "components" folder as below:

import React, { useEffect, useState } from 'react';


import axios from 'axios';

function FetchData(props) {
const [users,setUsers] = useState([]);

useEffect(() => {
axios.get('https://jsonplaceholder.typicode.com/users')
.then((userData) => {
console.log(userData)
setUsers(userData.data)
})
.catch((err) => {
console.log(err);
})
},[])

return (
<div>
<ul>
{
users.map(user => <li key={user.id}> {user.name} </li>)

}
</ul>
</div>
);
}

export default FetchData;

=> save and run


-----------------------------------------
=> Displaying data as a table:
FetchData.js:

import axios from 'axios';


import React, { useEffect, useState } from 'react';

function FetchData(props) {
const [users,setUsers] = useState([])
useEffect(() => {
axios.get('https://jsonplaceholder.typicode.com/users')
.then((userData) => {
console.log(userData)
setUsers(userData.data)
})
.catch((err) => {
console.log(err)
})
},[])
return (
<div class="container-flex">
<table class="table table-hover table-striped table-dark" >
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>USERNAME</th>
<th>EMAIL</th>
<th>CITY</th>
<th>PHONE</th>
</tr>
</thead>
<tbody>
{
users.map(user =>
<tr key="id">
<td>{user.id}</td>
<td>{user.name}</td>
<td>{user.username}</td>
<td>{user.email}</td>
<td>{user.address.city}</td>
<td>{user.phone}</td>
</tr>
)
}
</tbody>
</table>
</div>
);
}

export default FetchData;

=> save and run


============================================
CRUD Operations using React JS:

1) Create a new React project as:


npx create-react-app react-crud-app

=> Modify package.json as below:

"dependencies": {
"@testing-library/jest-dom": "^5.16.5",
"axios": "^0.27.2",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
},
--------------------------------------
=> Modify index.js as below:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';

ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
--------------------------------------
2) Change to project folder and install semantic-ui-react library as below:
npm install semantic-ui-react semantic-ui-css

=> Connect to the following url:


https://cdnjs.com/libraries/semantic-ui

=> Copy and paste the following url inside index.html:

<link rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.5.0/semantic.min.css"
integrity="sha512-KXol4x3sVoO+8ZsWPFI/r5KBVB/ssCGB5tsv2nVOKwLg33wTFP3fmnXa47FdSVIshV
TgsYk/1734xSk9aFIa4A==" crossorigin="anonymous" referrerpolicy="no-referrer" />

=> Now, index.html looks as below:

<!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" />
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<title>React App</title>
<link rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.5.0/semantic.min.css"
integrity="sha512-KXol4x3sVoO+8ZsWPFI/r5KBVB/ssCGB5tsv2nVOKwLg33wTFP3fmnXa47FdSVIshV
TgsYk/1734xSk9aFIa4A==" crossorigin="anonymous" referrerpolicy="no-referrer" />
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
</body>
</html>
---------------------------------------
3) Modify App.js as below:

import './App.css';

function App() {
return (
<div className='main'>
<h3>
CRUD Operations using React
</h3>
</div>
);
}

export default App;


----------------------------------------
=> Modify App.css as below:

.main{
display:flex;
justify-content: center;
align-items: center;
height:100vh;
flex-direction: column;
}

=> save and run


--------------------------------------
=> Create a folder named "components" folder and add the following components inside
it:
== Create.js
== Read.js
== Update.js
--------------------------------------
=> Connect to mockapi.io. login with your Gmail account. Create a project

=> The URL for the data source looks something like this:
https://64550208f803f34576379598.mockapi.io/Employee
========================5th may 2023====================================
<!-- Electricity Bill Application -->
<html>
<head>
<title>form validation</title>
<script>
function showBill()
{
pres = parseInt(f1.t1.value)
prev = parseInt(f1.t2.value)
if(pres<=prev)
{
alert("Present Reading must be greater than previous Reading")
f1.reset()
f1.t1.focus()
return false;
}
no_units = pres - prev
if(no_units < 100)
unit_price = 2.15;
else if(no_units < 200)
unit_price = 2.65
else
unit_price = 3.15
bill_amt = no_units * unit_price
f1.t3.value = no_units
f1.t4.value = unit_price
f1.t5.value = bill_amt
return false;
}
</script>
</head>
<body>
<h3 align="center">Electricity Bill Generation</h3>
<form name="f1" onsubmit="return showBill()" autocomplete="off">
<table cellpadding="5" align="center">
<tr>
<th>Present Reading : </th>
<th><input type="number" name="t1" required></th>
</tr>
<tr>
<th>Previous Reading : </th>
<th><input type="number" name="t2" required></th>
</tr>
<tr>
<th>No of units consumed : </th>
<th><input type="number" name="t3" readonly></th>
</tr>
<tr>
<th>Unit Price : </th>
<th><input type="number" name="t4" readonly></th>
</tr>
<tr>
<th>Bill Amount : </th>
<th><input type="number" name="t5" readonly></th>
</tr>
<tr>
<th><input type="submit" value="GENERATE BILL"></th>
<th><input type="reset" value="CANCEL"></th>
</tr>
</table>
</form>
</body>
</html>
------------------------------------------------------------------
<!-- Employee salary Geneartion -->
<html>
<head>
<title>form validation</title>
<script>
function validate()
{
x = f1.t4.selectedIndex
if(x == 0)
f1.t5.value = 50000.00
else if(x == 1)
f1.t5.value = 35000.00
else
f1.t5.value = 25000.00
alert("your data is valid")
return false;
}
</script>
</head>
<body>
<h3 align="center">Employee Salary Generation</h3>
<form name="f1" onsubmit="return validate()" autocomplete="off">
<table cellpadding="5" align="center">
<tr>
<th>Enter Employee Id : </th>
<th><input type="number" name="t1" min="101" max="199" required></th>
</tr>
<tr>
<th>Enter Employee Name : </th>
<th><input type="text" name="t2" minlength="4" maxlength="15" required></th>
</tr>
<tr>
<th>Select gender : </th>
<th >
<input type="radio" name="t3" value="M">M
<input type="radio" name="t3" value="F">F
</th>
<tr>
<th>Select Designation : </th>
<th><select name="t4">
<option value="manager">Manager</option>
<option value="accountant">Accountant</option>
<option value="clerk">Clerk</option>
</select></th>
</tr>
<tr>
<th>Employee Salary : </th>
<th><input type="number" name="t5" readonly></th>
</tr>
<tr>
<th><input type="submit" value="GENERATE BILL"></th>
<th><input type="reset" value="CANCEL"></th>
</tr>
</table>
</form>
</body>
</html>
--------------------------5th may 2023 html---------------------------------
CRUD Operations using React JS:

1) Create a new React project as:


npx create-react-app react-crud-app

=> Modify package.json as below:

"dependencies": {
"@testing-library/jest-dom": "^5.16.5",
"axios": "^0.27.2",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
},
--------------------------------------
=> Modify index.js as below:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';

ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
--------------------------------------
2) Change to project folder and install semantic-ui-react library as below:
npm install semantic-ui-react semantic-ui-css

=> Connect to the following url:


https://cdnjs.com/libraries/semantic-ui

=> Copy and paste the following url inside index.html:

<link rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.5.0/semantic.min.css"
integrity="sha512-KXol4x3sVoO+8ZsWPFI/r5KBVB/ssCGB5tsv2nVOKwLg33wTFP3fmnXa47FdSVIshV
TgsYk/1734xSk9aFIa4A==" crossorigin="anonymous" referrerpolicy="no-referrer" />

=> Now, index.html looks as below:

<!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" />
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<title>React App</title>
<link rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.5.0/semantic.min.css"
integrity="sha512-KXol4x3sVoO+8ZsWPFI/r5KBVB/ssCGB5tsv2nVOKwLg33wTFP3fmnXa47FdSVIshV
TgsYk/1734xSk9aFIa4A==" crossorigin="anonymous" referrerpolicy="no-referrer" />
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
</body>
</html>
---------------------------------------
3) Modify App.js as below:

import './App.css';

function App() {
return (
<div className='main'>
<h3>
CRUD Operations using React
</h3>
</div>
);
}

export default App;


----------------------------------------
=> Modify App.css as below:

.main{
display:flex;
justify-content: center;
align-items: center;
height:100vh;
flex-direction: column;
}

=> save and run


--------------------------------------
=> Create a folder named "components" folder and add the following components inside
it:
== Create.js
== Read.js
== Update.js
--------------------------------------
=> Connect to mockapi.io. login with your Gmail account. Create a project

=> The URL for the data source looks something like this:
https://64550208f803f34576379598.mockapi.io/Employee
======================================
=> Create a "form" using Semantic UI library:
=> Copy and paste the form code inside Create.js as below:

Create.js:

import React from 'react'


import { Button, Form } from 'semantic-ui-react'

const Create = () => (


<Form>
<Form.Field>
<label>Employee Name</label>
<input placeholder='Employee Name' />
</Form.Field>
<Form.Field>
<label>Designation</label>
<input placeholder='Designation' />
</Form.Field>
<Form.Field>
<label>Salary</label>
<input placeholder='Salary' />
</Form.Field>
<Button type='submit'>Insert Employee Data</Button>
</Form>
)

export default Create;


---------------------------------
=> Add the component inside App.js as below:

import './App.css';
import Create from './components/Create';

function App() {
return (
<div className='main'>
<h3>
CRUD Operations using React
</h3>
<div>
<Create />
</div>
</div>
);
}

export default App;

=> save and run


-------------------------------
=> Create the following state variables for Employee data inside Create.js as below:

import React, { useState } from 'react'


import { Button, Form } from 'semantic-ui-react'

const Create = () => {


const [name,setName] = useState('');
const [desg,setDesg] = useState('');
const [basic,setBasic] = useState(null);

const postData = () => {


console.log(name + " " + desg + " " + basic);
}

return(
<Form>
<Form.Field>
<label>Employee Name</label>
<input placeholder='Employee Name'
onChange={(e) => setName(e.target.value)} />
</Form.Field>
<Form.Field>
<label>Designation</label>
<input placeholder='Designation'
onChange={(e) => setDesg(e.target.value)} />
</Form.Field>
<Form.Field>
<label>Salary</label>
<input placeholder='Salary'
onChange={(e) => setBasic(e.target.value)} />
</Form.Field>
<Button type='submit' onClick={postData} >Insert Employee Data</Button>
</Form>
)}

export default Create;

=> Save and run


=> Type some employee data and click submit button.
=> See the employee data in the console
--------------------------------------------
=> To perform http requests to the Mock API URL, install axios as below:
npm install axios
--------------------------------------------
=> Now, let's perform insert operation inside Create.js as below:

import axios from 'axios';


import React, { useState } from 'react'
import { Button, Form } from 'semantic-ui-react'

const Create = () => {


const [name,setName] = useState('');
const [desg,setDesg] = useState('');
const [basic,setBasic] = useState(null);

const postData = () => {


axios.post('https://64550208f803f34576379598.mockapi.io/Employee',{
name,desg,basic
})
alert("Data Inserted Successfully")
}

return(
<Form>
<Form.Field>
<label>Employee Name</label>
<input placeholder='Employee Name'
onChange={(e) => setName(e.target.value)} />
</Form.Field>
<Form.Field>
<label>Designation</label>
<input placeholder='Designation'
onChange={(e) => setDesg(e.target.value)} />
</Form.Field>
<Form.Field>
<label>Salary</label>
<input placeholder='Salary'
onChange={(e) => setBasic(e.target.value)} />
</Form.Field>
<Button type='submit' onClick={postData} >Insert Employee Data</Button>
</Form>
)}

export default Create;

=> save and run


=> Insert a record and click submit button
=> Refresh the URL in mockapi to see the result
====================================
=> Install react-router-dom as below:
npm install react-router-dom@5.2.0
-------------------------------------
=> Create Hyperlinks in App.js as below:

import './App.css';
import Create from './components/Create';
import Read from './components/Read';
import Update from './components/Update';

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

function App() {
return (
<div className='main'>
<h3>
CRUD Operations using React
</h3>
<Router>
<Link to="/create">Create</Link>
<Link to="/read">Read</Link>
<Link to="/update">Update</Link>

<Switch>
<Route exact path="/create">
<Create />
</Route>
<Route exact path="/read">
<Read />
</Route>
<Route exact path="/update">
<Update />
</Route>
</Switch>
</Router>

</div>
);
}

export default App;

=> save and run


=======================================
Performing the Read Operation:
=> Modify Read.js as below:

import axios from 'axios';


import React, { useEffect, useState } from 'react'
import { Table,Button, TableCell } from 'semantic-ui-react';
const Read = () => {

const [EmpData,setEmpData] = useState([]);

useEffect(() => {
axios.get('https://64550208f803f34576379598.mockapi.io/Employee')
.then((apiData) => {
setEmpData(apiData.data)
console.log(EmpData)
})
.catch((err) => {
console.log(err)
})
},[])

return(
<Table celled>
<Table.Header>
<Table.Row>
<Table.HeaderCell>Emp ID</Table.HeaderCell>
<Table.HeaderCell>Emp Name</Table.HeaderCell>
<Table.HeaderCell>Designation</Table.HeaderCell>
<Table.HeaderCell>Salary</Table.HeaderCell>
</Table.Row>
</Table.Header>

<Table.Body>
{
EmpData.map((data) => {
return(
<Table.Row>
<Table.Cell> {data.id} </Table.Cell>
<Table.Cell> {data.name} </Table.Cell>
<Table.Cell> {data.desg} </Table.Cell>
<Table.Cell> {data.basic} </Table.Cell>
</Table.Row>
)
})
}
</Table.Body>
</Table>
)}

export default Read;

=> save and run


-------------------------------------
Performing Update Operation:
=> Add one more column inside the table of Read.js as below:
import axios from 'axios';
import React, { useEffect, useState } from 'react'
import { Table,Button, TableCell } from 'semantic-ui-react';

const Read = () => {

const [EmpData,setEmpData] = useState([]);

useEffect(() => {
axios.get('https://64550208f803f34576379598.mockapi.io/Employee')
.then((apiData) => {
setEmpData(apiData.data)
console.log(EmpData)
})
.catch((err) => {
console.log(err)
})
},[])

const setData = (data) => {


console.log(data);
}

return(
<Table celled>
<Table.Header>
<Table.Row>
<Table.HeaderCell>Emp ID</Table.HeaderCell>
<Table.HeaderCell>Emp Name</Table.HeaderCell>
<Table.HeaderCell>Designation</Table.HeaderCell>
<Table.HeaderCell>Salary</Table.HeaderCell>
<Table.HeaderCell>Update</Table.HeaderCell>
</Table.Row>
</Table.Header>

<Table.Body>
{
EmpData.map((data) => {
return(
<Table.Row>
<Table.Cell> {data.id} </Table.Cell>
<Table.Cell> {data.name} </Table.Cell>
<Table.Cell> {data.desg} </Table.Cell>
<Table.Cell> {data.basic} </Table.Cell>
<Table.Cell>
<Button onClick={() => setData(data)}>
Update
</Button>
</Table.Cell>
</Table.Row>
)
})
}
</Table.Body>
</Table>
)}

export default Read;

=> save and run


=> Click the update button at any record and see the record information on the
console
---------------------------------
=> Now, the Employee data selected in Read.js must be sent to Update.js
=> Create a hyperlink for Update button so that when this link is clicked Update.js
component must be loaded
=> For this, we use localStorage object as below:
=> Read.js:

import axios from 'axios';


import React, { useEffect, useState } from 'react'
import { Table,Button } from 'semantic-ui-react';
import { Link } from 'react-router-dom';

const Read = () => {

const [EmpData,setEmpData] = useState([]);

useEffect(() => {
axios.get('https://64550208f803f34576379598.mockapi.io/Employee')
.then((apiData) => {
setEmpData(apiData.data)
console.log(EmpData)
})
.catch((err) => {
console.log(err)
})
},[])

const setData = (data) => {


let {id,name,desg,basic} = data; // Object destructuring
localStorage.setItem("ID",id);
localStorage.setItem("Name",name);
localStorage.setItem("Desg",desg);
localStorage.setItem("Basic",basic);
}

return(
<Table celled>
<Table.Header>
<Table.Row>
<Table.HeaderCell>Emp ID</Table.HeaderCell>
<Table.HeaderCell>Emp Name</Table.HeaderCell>
<Table.HeaderCell>Designation</Table.HeaderCell>
<Table.HeaderCell>Salary</Table.HeaderCell>
<Table.HeaderCell>Update</Table.HeaderCell>
</Table.Row>
</Table.Header>

<Table.Body>
{
EmpData.map((data) => {
return(
<Table.Row>
<Table.Cell> {data.id} </Table.Cell>
<Table.Cell> {data.name} </Table.Cell>
<Table.Cell> {data.desg} </Table.Cell>
<Table.Cell> {data.basic} </Table.Cell>
<Link to="/update">
<Table.Cell>
<Button onClick={() => setData(data)}>
Update
</Button>
</Table.Cell>
</Link>
</Table.Row>
)
})
}
</Table.Body>
</Table>
)}

export default Read;

=> save and run


=====================================
=> Now, read the data from localStorage object into Update.js as below:

import React, { useEffect, useState } from 'react';


import {Form,Button} from 'semantic-ui-react';

function Update(props) {
const [id,setId] = useState(null);
const [name,setName] = useState('');
const [desg,setDesg] = useState('');
const [basic,setBasic] = useState(null);

useEffect( () => {
setId(localStorage.getItem('ID'))
setName(localStorage.getItem('Name'))
setDesg(localStorage.getItem('Desg'))
setBasic(localStorage.getItem('Basic'))
})

return (
<div>
<Form className='create-form'>
<Form.Field>
<label> Name </label>
<input value={name}
onChange = {(e) => setName(e.target.value)} />
</Form.Field>
<Form.Field>
<label> Designation </label>
<input value={desg}
onChange = {(e) => setDesg(e.target.value)} />
</Form.Field>
<Form.Field>
<label> Basic Salary </label>
<input value={basic}
onChange = {(e) => setBasic(e.target.value)} />
</Form.Field>
</Form>
</div>
);
}

export default Update;

=> Click the "Update" button of any record in Read.js. Now, we can see the record
information inside the form of Update.js
========================================
=> Now, create a button in Update.js so that when the update button is clicked the
data must be update in the API
=> Update.js:

import axios from 'axios';


import React, { useEffect, useState } from 'react';
import {Form,Button} from 'semantic-ui-react';

function Update(props) {
const [id,setId] = useState(null);
const [name,setName] = useState('');
const [desg,setDesg] = useState('');
const [basic,setBasic] = useState(null);

useEffect( () => {
setId(localStorage.getItem('ID'))
setName(localStorage.getItem('Name'))
setDesg(localStorage.getItem('Desg'))
setBasic(localStorage.getItem('Basic'))
},[])

const updateEmpData = () => {


axios.put(`https://64550208f803f34576379598.mockapi.io/Employee/${id}`,
{
name,desg,basic
})
alert("Record Updated Successfully")
}

return (
<div>
<Form className='create-form'>
<Form.Field>
<label> Name </label>
<input value={name}
onChange = {(e) => setName(e.target.value)} />
</Form.Field>
<Form.Field>
<label> Designation </label>
<input value={desg}
onChange = {(e) => setDesg(e.target.value)} />
</Form.Field>
<Form.Field>
<label> Basic Salary </label>
<input value={basic}
onChange = {(e) => setBasic(e.target.value)} />
</Form.Field>
<Button onClick={updateEmpData}>
Update Employee Data
</Button>
</Form>
</div>
);
}

export default Update;

=> Select a record from Read.js


=> Modify the record values
=> Click the Update Employee Data button
=> See the result in the API
-------------------------------------------------
Deleting the record:
=> Create a button named "DELETE" inside Read.js as below:

import axios from 'axios';


import React, { useEffect, useState } from 'react'
import { Table,Button } from 'semantic-ui-react';
import { Link } from 'react-router-dom';

const Read = () => {

const [EmpData,setEmpData] = useState([]);

useEffect(() => {
axios.get('https://64550208f803f34576379598.mockapi.io/Employee')
.then((apiData) => {
setEmpData(apiData.data)
console.log(EmpData)
})
.catch((err) => {
console.log(err)
})
},[])

const setData = (data) => {


let {id,name,desg,basic} = data; // Object destructuring
localStorage.setItem("ID",id);
localStorage.setItem("Name",name);
localStorage.setItem("Desg",desg);
localStorage.setItem("Basic",basic);
}

const delData = (id) => {


axios.delete(`https://64550208f803f34576379598.mockapi.io/Employee/${id}`);
alert("Record Deleted Successfully");
}

return(
<Table celled>
<Table.Header>
<Table.Row>
<Table.HeaderCell>Emp ID</Table.HeaderCell>
<Table.HeaderCell>Emp Name</Table.HeaderCell>
<Table.HeaderCell>Designation</Table.HeaderCell>
<Table.HeaderCell>Salary</Table.HeaderCell>
<Table.HeaderCell>Update</Table.HeaderCell>
<Table.HeaderCell>Delete</Table.HeaderCell>
</Table.Row>
</Table.Header>

<Table.Body>
{
EmpData.map((data) => {
return(
<Table.Row>
<Table.Cell> {data.id} </Table.Cell>
<Table.Cell> {data.name} </Table.Cell>
<Table.Cell> {data.desg} </Table.Cell>
<Table.Cell> {data.basic} </Table.Cell>
<Link to="/update">
<Table.Cell>
<Button onClick={() => setData(data)}>
Update
</Button>
</Table.Cell>
</Link>
<Table.Cell>
<Button onClick={() => delData(data.id)}>
Delete
</Button>
</Table.Cell>
</Table.Row>
)
})
}
</Table.Body>
</Table>
)}

export default Read;

=> Save and run


=> Click on the "Delete" button in Read component.
=> Refresh the page to see the result
=> Check whether the record was deleted in the URL also

You might also like