React Js
React Js
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);
2.
--------------------------------------------------------------------------
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>
--------------------------------------
/* 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
--------------------------------------------
* ES6 has provide let and const ketowrd
--------------------------------------------
* functions in JS:
----------------------------------------------
/* 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")
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) :
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:
=> with the help of the object, we can access the data members using the dot(.)
operator.
obj-name.datamember;
syntax:
constuctor(){
---------------------------------
* 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.
=> 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:
== Once project is build, change to project folder and run the application as:
npm start
function App() {
return (
<div>
<h1 align='center'>Welcome to React</h1>
</div>
);
}
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
function App() {
return (
<div>
<h3 align='center'>IMplementing App component as normal function</h3>
</div>
);
}
function FunComp(props) {
return (
<div>
<h3 align='center'>Inside FunComp</h3>
</div>
);
}
<div>
<h3 align='center'>
Implementing FunComp as lamda function
</h3>
</div>
import './App.css';
import FunComp from './components/FunComp';
function App() {
return (
<div>
<FunComp name="APEC" location="Ameerpet"/>
<FunComp name="Datadot" location="Begumpet"/>
</div>
);
}
function FunComp(props) {
return (
<div>
<h3 align='center'>
{props.name} is located at {props.location}
</h3>
</div>
);
}
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>
);
}
function FunComp(props) {
return (
<div>
<h3 align='center'>
{props.name} is the faculty of {props.subject}
</h3>
</div>
);
}
import './App.css';
import FunComp from './components/FunComp';
function App() {
return (
<div>
<FunComp name='suresh' subject='Java'/>
</div>
);
}
function FunComp(props) {
props.name = 'Ramesh';
return (
<div>
<h3 align='center'>
{props.name} is the faculty of {props.subject}
</h3>
</div>
);
}
import './App.css';
import './App.css';
=> ClassComp.js
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.
import './App.css';
</h3>
</div>
);
}
}
</h3>
</div>
);
}
}
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)
import './App.css';
import FormComp from './components/FormComp';
1. Inline styles
2. CSS stylesheet
3. CSS modules
Eg:
=> create a file named "Inline.js" inside "components" folder and add that component
in the App.js as below:
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>
);
}
import './App.css';
import Inline from './components/Inline';
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>
);
}
.class1{
color:red;
background-color: black;
}
.class2{
color:blue;
background-color: cyan;
}
.class3{
color:green;
background-color: yellow;
}
----------------------------------------------------------
=> import the mystyle.css inside App.js as below:
import './App.css';
import Inline from './components/Inline';
import './components/mystyles.css'
import './App.css';
import Inline from './components/Inline';
import './components/mystyles.css'
--------------------------------------------------------------
* 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.
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 './App.css';
import Inline from './components/Inline';
import styles from './components/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>
);
}
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>
);
}
---------------------------------------------------------------------
* Implementing Bootstrap in React:
<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
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
=> 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';
-----------------------------------------------
2. Installing using npm
=> before installing remove the CDN from index.html
=> install bootstrap using as below:
npm install font-awesome@4.7.0
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
* 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"
},
.....
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>
);
}
function Services(props) {
return (
<div>
<h3 align="center">Inside Services</h3>
</div>
);
}
function ContactUs(props) {
return (
<div>
<h3 align="center">Inside ContactUs</h3>
</div>
);
}
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>
);
}
------------------------------------------------
=> 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>
);
}
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:
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>
);
}
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>
);
}
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>
);
}
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>
);
}
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>
);
}
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>
);
}
=> 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:
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>
);
}
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>
);
}
"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
<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" />
<!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>
);
}
.main{
display:flex;
justify-content: center;
align-items: center;
height:100vh;
flex-direction: column;
}
=> 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:
"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
<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" />
<!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>
);
}
.main{
display:flex;
justify-content: center;
align-items: center;
height:100vh;
flex-direction: column;
}
=> 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 './App.css';
import Create from './components/Create';
function App() {
return (
<div className='main'>
<h3>
CRUD Operations using React
</h3>
<div>
<Create />
</div>
</div>
);
}
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>
)}
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>
)}
import './App.css';
import Create from './components/Create';
import Read from './components/Read';
import Update from './components/Update';
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>
);
}
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>
)}
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.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>
)}
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.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>
)}
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>
);
}
=> 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:
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>
<Button onClick={updateEmpData}>
Update Employee Data
</Button>
</Form>
</div>
);
}
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.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>
)}