React Basics: Create Elements & Components
React Basics: Create Elements & Components
************************************************
<html>
<head>
<script crossorigin
src="[Link]
<script crossorigin src="[Link]
[Link]"></script>
</head>
<body>at
<div id="example"></div>
<script>
const reactEle = [Link]('h1', {}, 'My First React App');
const domEle = [Link]('example');
const root = [Link](domEle);
[Link](reactEle);
</script>
</body>
</html>
Note: React object is available(can be used in console like other objects)
Program-8: Fragments
*********************
import React from 'react';
class Header extends [Link] {
render() {
return (
<[Link]>
<div>I am an element!</div>
<button>I am another element</button>
</[Link]>
);
}
}
export default Header;
program-11 : CSS
****************
import React from 'react';
class App extends [Link] {
render() {
var myStyle={
color:'blue',
backgroundColor:'yellow',
border:'5px solid green'
}
return (
<div>
Hello World!!!
<p style={{color:'red',fontSize:'42px'}}>this is paragraph</p>
<div style={myStyle}>this is a div</div>
</div>
);
}
}
export default App;
-------------
[Link]
--------------
.error{
background-color:yellow;
}
-------------
import React from 'react';
import styles from './[Link]';
import './[Link]';
-------------------(OR)--------------------------------------
import React, { Component } from 'react';
export default class Demo extends Component {
render() {
let employees = [
{ eId: 101, name: "sanjay", sal: 5000 },
{ eId: 104, name: "deepak", sal: 8000 },
{ eId: 103, name: "ranjan", sal: 7000 },
{ eId: 102, name: "manoj", sal: 9000 }
]
const empRows = [];
for (let emp of employees) {
const row = (
<tr key={[Link]}>
<td>{[Link]}</td>
<td>{[Link]}</td>
<td>{[Link]}</td>
</tr>
);
[Link](row);
}
return (
<table className='table table-bordered table-striped'>
<thead>
<tr>
<th>Emp Id</th>
<th>Name</th>
<th>Salary</th>
</tr>
</thead>
<tbody>
{empRows}
</tbody>
</table>
);
}
}
program-25: Props
******************
import React from 'react';
import Child from '../child/child';
class Parent extends [Link] {
render() {
let user = { name: 'sachin', age: 35 }
return (
<div>
This is Parent Component
<Child name={[Link]} age={[Link]} />
</div>
);
}
}
export default Parent;
-------------------
import React from 'react';
class Child extends [Link] {
render() {
return (
<div>
<h2>This is child component</h2>
<h2>{[Link]}--{[Link]}</h2>
</div>
);
}
}
export default Child;
Program-27 propTypes
*******************
import React from 'react';
import { PropTypes } from 'prop-types';
class Student extends [Link] {
render() {
return (
<div>
<p>Student Name: {[Link]}</p>
<p>Age: {[Link]}</p>
</div>
);
}
}
[Link] = {
name: [Link],
age: [Link]
};
export default Student;
Program-29: [Link]
**************************
import React from 'react';
import Greet from '../greet/greet';
class Content extends [Link] {
render() {
return (
<div>
<Greet>
<p>I am child-1</p>
<p>I am child-2</p>
</Greet>
<Greet>
<p>I am child-1</p>
<p>I am child-2</p>
</Greet>
</div>
);
}
}
export default Content;
-----------------------------
import React from 'react';
class Greet extends [Link] {
render() {
return (
<h2>
This is Greet Component
{[Link]}
</h2>
);
}
}
export default Greet;
Program-31: States
******************
class Counter extends [Link] {
constructor(props) {
super(props);
[Link] = {count: 0 };
}
increment = () => {
[Link]({count: [Link] + 1});
}
render() {
return (
<div>
<div>count:{[Link]}</div>
<button onClick={[Link]}>click!</button>
</div>
);
}
};
Program-35 Show/Hide
*********************
import React from 'react';
class MyClass extends [Link] {
constructor(props) {
super(props);
[Link] = { flag: true };
}
toggleFlag = () => {
[Link]({ flag: ![Link] });
}
render() {
return (
<div>
{[Link] ? <div>Hellllllo</div> : null}
<button onClick={[Link]}>
{[Link] ? 'HIDE' : 'SHOW'}
</button>
</div>
);
}
}
export default MyClass;
--------------------------------------
import React, { useState } from 'react';
export default function Demo() {
const [flag, toggleFlag] = useState(true);
const toggle = function () {
toggleFlag(!flag)
}
return (
<div>
{flag ? <div>Hellllllo</div> : null}
<button onClick={toggle}>
{flag ? 'HIDE' : 'SHOW'}
</button>
</div>
)
}
return (
<div>
<input type={[Link] ? 'password' : 'text'} />
<button onClick={[Link]}>{[Link] ? 'Show
password' : 'Hide password'}</button>
</div>
)
}
}
------------------------------------------------
import React, { useState } from "react";
return <>
<h2>Toggle Dark/Light Mode</h2>
<div>This page is in <b>{isDark ? 'Dark' : 'Light'}</b> Mode</div>
<button onClick={changeMode}>Go To {!isDark ? 'Dark' : 'Light'}
Mode</button>
</>
}
======
.dark{
background-color:black;
color:white
}
Program-39 Addition
*******************
import React from 'react';
<h2>Addition is {[Link]}</h2>
<button onClick={[Link]}>Addddddd</button>
</div>
);
}
}
export default Addition;
----------------------------------------------------
import React, { useState } from 'react'
export default function Demo() {
const [num1, setnum1] = useState(0);
const [num2, setnum2] = useState(0);
const [total, settotal] = useState(0);
return (
<div>
<div>
<input type="number" onKeyUp={(e) => {
setnum1(+[Link]);
}} />
<input type="number" onKeyUp={(e) => {
setnum2(+[Link]);
}} />
if ([Link]) { // if folder
return <div>
<span onClick={() => setExpand(!expand)} style={{ cursor: 'pointer' }}>
📁
{[Link]}
<br />
</span>
<div
style={{ display: expand ? "block" : "none", paddingLeft: "20px" }}
>
{[Link]((subfolderInfo, ind) => (
<Folder folderInfo={subfolderInfo} key={ind} />
))}
</div>
</div>
} else { // if file
return <span>
🏢
{[Link]} <br />
</span>
}
}
const config = {
red: { backgroundColor: 'red', duration: 4000, next: 'green' },
yellow: { backgroundColor: 'yellow', duration: 1000, next: 'red' },
green: { backgroundColor: 'green', duration: 3000, next: 'yellow' }
};
export default function TrafficLight() {
const [currentColor, setCurrentColor] = useState('green');
useEffect(() => {
const { duration, next } = config[currentColor];
const timerId = setTimeout(() => {
setCurrentColor(next);
}, duration);
return () => {
clearTimeout(timerId);
};
}, [currentColor]);
Program: 41 Search
******************
import React, { useState } from "react";
import SearchBar from "react-js-search";
return (
<>
<SearchBar
// onSearchTextChange={onSearchTextChange}
onSearchButtonClick={onSearchClick}
placeHolderText={"Search here..."}
data={employees}
/>
<button onClick={sortAsc}>Asc</button>
<button onClick={sortDesc} className='ms-1'>Desc</button>
<hr />
{
<table className="table table-bordered">
<tbody>
{[Link]((emp, ind) => (
<tr key={ind}>
<td>{[Link]}</td>
<td>{[Link]}</td>
<td>{[Link]}</td>
</tr>
))}
</tbody>
</table>
}
</>
);
}
Program-42 Pagination
************************
import React, { useState } from "react";
import productsArr from "./[Link]";
import ReactPaginate from "react-paginate";
import "./[Link]";
export default function ProductsPagination() {
const [itemOffset, setItemOffset] = useState(0);
const itemsPerPage = 4;
return (
<>
<h1 className="text-center">Products With Pagination</h1>
<div className="container">
<div className="row">
{[Link]((product) => (
<div className="col-sm-3" key={[Link]}>
<div className="card text-center">
<img
src={[Link]}
className="card-img-top"
alt="..."
style={{ height: "200px" }}
/>
<div className="card-body">
<h5 className="card-title">{[Link]}</h5>
<p className="card-text">{[Link]}</p>
<p
className="card-text"
style={{ height: "200px", overflow: "scroll" }}
>
{[Link]}
</p>
<p className="card-text"> {[Link]}</p>
<a href="#" className="btn btn-primary">
BUY NOW
</a>
</div>
</div>
</div>
))}
</div>
</div>
<ReactPaginate
breakLabel="..."
nextLabel="next >"
onPageChange={handlePageClick}
pageRangeDisplayed={5}
pageCount={pageCount}
previousLabel="< previous"
renderOnZeroPageCount={null}
containerClassName="pagination"
pageLinkClassName="page-num"
previousLinkClassName="page-num"
nextLinkClassName="page-num"
activeLinkClassName="active"
/>
</>
);
}
[Link]
=======================
.pagination {
list-style: none;
display: flex;
justify-content: center;
align-items: center;
margin: 10px;
font-size: 16px;
gap: 5px;
}
.pagination .page-num {
padding: 10px 15px;
cursor: pointer;
border-radius: 5px;
font-weight: bold;
text-decoration: none;
}
.pagination .page-num:hover {
background-color: aqua;
color: white;
}
.pagination .active {
background-color: aqua;
}
Assignment
==========
-add 2 input boxes (num1,num2)
-add a button, onClick of button find the addition Result
Program-45 Modal
******************
1. npm i react-modal
2. add the below code
function openModal() {
setIsOpen(true);
}
function closeModal() {
setIsOpen(false);
}
return (
<div>
<button onClick={openModal}>Open Modal</button>
<Modal
isOpen={modalIsOpen}
onRequestClose={closeModal}
contentLabel="Example Modal"
shouldCloseOnOverlayClick={false}
>
<button onClick={closeModal}>close</button>
<div>I am a modal</div>
<div>this is a div</div>
<input />
</Modal>
</div>
)
}
render() {
return (
<div>
<table border='1' align='center' width='50%'>
<tr>
<th>Sl No.</th>
<th>Emp Id</th>
<th>Name</th>
<th>Salary</th>
<th>Action</th>
</tr>
{[Link]((emp, ind) => (
<tr key={[Link]}>
<td>{ind}</td>
<td>{[Link]}</td>
<td>{[Link]}</td>
<td>{[Link]}</td>
<td>
<button onClick={() =>
[Link](ind)}>Delete</button>
<button onClick={() =>
[Link](emp)}>View</button>
</td>
</tr>
))}
</table>
Emp Id:
<input onKeyUp={[Link]}></input> <br></br><br></br>
Name:
<input onKeyUp={[Link]}></input> <br></br><br></br>
Salary:
<input onKeyUp={[Link]}></input> <br></br><br></br>
</div>
);
}
}
export default Crud;
return <>
<h2 className='text-center'>This is EmployeeCRUD Component</h2>
<div className='container'>
<div className='row'>
<div className='col-sm-8'>
<h3>Employee List</h3>
<EmployeeList
employees={employees}
deleteEmployee={deleteEmployee}
editEmployee={editEmployee}
/>
</div>
<div className='col-sm-4'>
{
isEdit ?
<EditEmployee
selectedEmployee={selectedEmployee}
saveEditedEmployee={saveEditedEmployee}
cancelSave={cancelSave}
/>
:
<AddEmployee addEmployee={addEmployee} />
}
</div>
</div>
</div>
</>
}
------------------------------------------------
import React from 'react'
import { useState } from 'react';
------------------------------------------------
import React, { useState } from 'react'
function Demo2(props) {
[Link]("demo-2 render called");
return (
<div>
Demo2
{[Link]((car) => {
return <li>{car}</li>;
})}
</div>
);
}
export default [Link](Demo2);
program-51 componentDidMount
******************************
class Header extends [Link] {
constructor(props) {
super(props);
[Link] = {favoritecolor: "red"};
}
componentDidMount() {
setTimeout(() => {
[Link]({favoritecolor: "yellow"})
}, 1000)
}
render() {
return (
<h1>My Favorite Color is {[Link]}</h1>
);
}
}
Program-52 shouldComponentUpdate
**********************************
class Header extends [Link] {
constructor(props) {
super(props);
[Link] = {favoritecolor: "red"};
}
shouldComponentUpdate() {
return false;
}
changeColor = () => {
[Link]({favoritecolor: "blue"});
}
render() {
return (
<div>
<h1>My Favorite Color is {[Link]}</h1>
<button type="button" onClick={[Link]}>Change color</button>
</div>
);
}
}
Program-53 getSnapshotBeforeUpdate
************************************
class Header extends [Link] {
constructor(props) {
super(props);
[Link] = {favoritecolor: "red"};
}
componentDidMount() {
setTimeout(() => {
[Link]({favoritecolor: "yellow"})
}, 1000)
}
getSnapshotBeforeUpdate(prevProps, prevState) {
[Link]("div1").innerHTML =
"Before the update, the favorite was " + [Link];
}
componentDidUpdate() {
[Link]("div2").innerHTML =
"The updated favorite is " + [Link];
}
render() {
return (
<div>
<h1>My Favorite Color is {[Link]}</h1>
<div id="div1"></div>
<div id="div2"></div>
</div>
);
}
}
program-54 componentDidUpdate
*********************************
class Header extends [Link] {
constructor(props) {
super(props);
[Link] = {favoritecolor: "red"};
}
componentDidMount() {
setTimeout(() => {
[Link]({favoritecolor: "yellow"})
}, 1000)
}
componentDidUpdate() {
[Link]("mydiv").innerHTML =
"The updated favorite is " + [Link];
}
render() {
return (
<div>
<h1>My Favorite Color is {[Link]}</h1>
<div id="mydiv"></div>
</div>
);
}
}
program-60 (componentWillUnmount)
*********************************
class Container extends [Link] {
constructor(props) {
super(props);
[Link] = {show: true};
}
delHeader = () => {
[Link]({show: false});
}
render() {
let myheader;
if ([Link]) {
myheader = <Child />;
};
return (
<div>
{myheader}
<button type="button" onClick={[Link]}>Delete Header</button>
</div>
);
}
}
useEffect(() => {
[Link]("use effect called");
}, [a,b]);
return (
<>
<div>Demo</div>
<div>
{a} {b} {c}
</div>
<button onClick={() => setA(15)}>
update A
</button>
<button onClick={() => setB(25)}>
update B
</button>
<button onClick={() => setC(35)}>
update C
</button>
</>
);
}
}
--------------------------------------------------
import React, { useRef } from "react";
export default function Addition() {
const inputRef1 = useRef();
const inputRef2 = useRef();
return (
<div>
num1: <input ref={inputRef1} />
num2: <input ref={inputRef2} />
<button onClick={add}>Add</button>
</div>
);
}
return (
<div>
num1: <input ref={input => { inputRef1 = input; }} />
num2: <input ref={input => { inputRef2 = input; }} />
<button onClick={add}>Add</button>
</div>
);
}
program- 66 Ref Forwarding
***************************
import React, { Component } from 'react'
import FancyButton from '../FancyButton/FancyButton'
return (
<div style={{ padding: 20 }}>
<h2>Search Filter</h2>
<input
value={query}
onChange={e => setQuery([Link])}
placeholder="Type to search"
/>
<p>Showing {[Link]} results</p>
<ul>
{[Link](0, 20).map(i => (
<li key={i}>{i}</li>
))}
</ul>
</div>
);
}
return (
<>
<form onSubmit={submitHandler}>
First Name:
<input name="fname" value={fname} onChange={(e) =>
setFname([Link])} />
Last Name:
<input name="lname" value={lname} onChange={(e) =>
setLname([Link])} />
<br />
<br />
<button>submit</button>
</form>
</>
);
}
return (
<>
<form onSubmit={submitHandler}>
First Name:
<input
name="fname"
value={[Link]}
onChange={(e) => setUser({ ...user, fname: [Link] })}
/>
Last Name:
<input
name="lname"
value={[Link]}
onChange={(e) => setUser({ ...user, lname: [Link] })}
/>
<br />
<br />
state data: {[Link] + " " + [Link]}
<button>submit</button>
</form>
</>
);
}
return (
<>
<form onSubmit={submitHandler}>
First Name:
<input name="fname" value={fname} onChange={changeHandler} />
<span class="text-danger">{fNameErrorMsg}</span> <br/>
Last Name:
<input name="lname" value={lname} onChange={changeHandler} />
<span class="text-danger">{lNameErrorMsg}</span>
<br /><br />
<button>submit</button>
</form>
</>
);
}
</textarea>
</p>
<input type='reset' value='Clear' className='mx-2 btn
btn-danger'
onClick={handleReset} />
<input type='submit' value='Submit' className='btn btn-
primary' disabled={!isFormValid} />
</form>
<pre>
{[Link](formData,null,4)}
</pre>
</div>
</div>
</div>
</div>
</>
}
const initialFormValue = {
name: "", email: "", password: "", confirmPassword: "",
gender: "", role: "", skills: [], acceptTerms: false
}
const skillsList = ["JavaScript", "React", "[Link]", "Python"];
const validationSchema = [Link]({
name: [Link]().required("Name is required"),
email: [Link]()
.email("Invalid email address")
.required("Email is required"),
password: [Link]()
.min(6, "Password must be at least 6 characters")
.required("Password is required"),
confirmPassword: [Link]()
.oneOf([[Link]("password"), null], "Passwords must match")
.required("Confirm password is required"),
gender: [Link]().required("Gender is required"),
role: [Link]().required("Role is required"),
skills: [Link]().min(1, "Select at least one skill"),
acceptTerms: [Link]().oneOf([true], "You must accept the terms"),
});
return <>
<h3 className='text-center'>React Form Using Formik & Yup</h3>
<div className='col-sm-6 offset-sm-3'>
<div className='border border-3 rounded-3 p-2 m-2'>
<Formik
initialValues={initialFormValue}
validationSchema={validationSchema}
onSubmit={(values, { resetForm }) => {
setFormData(values);
resetForm();
}}
>
{({ values, isSubmitting }) => (
<Form>
<div className='my-1'>
<label>Name:</label>
<Field name="name" type="text" />
<div className="text-danger"><ErrorMessage
name="name" /></div>
</div>
<div className='my-1'>
<label>Email:</label>
<Field name="email" type="email" />
<div className="text-danger"><ErrorMessage
name="email" /></div>
</div>
<div className='my-1'>
<label>Password:</label>
<Field name="password" type="password" />
<div className="text-danger"><ErrorMessage
name="password" /></div>
</div>
<div className='my-1'>
<label>Confirm Password:</label>
<Field name="confirmPassword" type="password" />
<div className="text-danger"><ErrorMessage
name="confirmPassword" /></div>
</div>
<div className='my-1'>
<label>Gender:</label>
<Field as="select" name="gender">
<option value="">Select</option>
<option value="male">Male</option>
<option value="female">Female</option>
</Field>
<div className="text-danger"><ErrorMessage
name="gender" /></div>
</div>
<div className='my-1'>
<label>Role:</label>
<label>
<Field type="radio" name="role"
value="developer" />
Developer
</label>
<label>
<Field type="radio" name="role"
value="designer" />
Designer
</label>
<div className="text-danger"><ErrorMessage
name="role" /></div>
</div>
<div className='my-1'>
<label>Skills:</label>
{[Link]((skill) => (
<label key={skill} style={{ display:
"block" }}>
<Field
type="checkbox"
name="skills"
value={skill}
/>
{skill}
</label>
))}
<div className="text-danger"><ErrorMessage
name="skills" /></div>
</div>
<div className='my-1'>
<label>
<Field type="checkbox" name="acceptTerms" />
I accept the terms and conditions
</label>
<div className="text-danger"><ErrorMessage
name="acceptTerms" /></div>
</div>
<button type="submit" disabled={isSubmitting}
style={{ marginTop: "10px" }}>
Submit
</button>
</Form>
)}
</Formik>
{formData && (
<div style={{ marginTop: "20px", background: "#f9f9f9",
padding: "15px" }}>
<h3>Submitted Data:</h3>
<pre>{[Link](formData, null, 2)}</pre>
</div>
)}
</div>
</div>
</>
}
if ([Link] < 5) {
err1 = <strong>Your name mustcontain 5 chars</strong>;
}
if ([Link] !== "" && !Number([Link])) {
err2 = <strong>Your age must be a number</strong>;
}
[Link]({ nameErrorMsg: err1, ageErrorMsg: err2 });
//alert("You are submitting " + [Link] + " " +
[Link]);
}
render() {
return (
<form onSubmit={[Link]}>
<h1>Hello {[Link]} {[Link]}</h1>
<p>Enter your name:</p>
<input
type='text'
name='username'
onChange={[Link]}
/>
{[Link]}
<br></br>
<input type="submit" />
</form>
);
}
}
export default MyForm;
Program-77 DropDown
********************
class MyForm extends [Link] {
import React, { Component } from 'react'
fetchUsers = () => {
const myURL = '[Link]
fetch(myURL)
.then((response) => [Link]())
.then((data) => {
[Link](data);
[Link]({ 'users': data })
});
}
componentDidMount() {
[Link]();
}
render() {
return (
<table className='table table-bordered table-striped'>
<thead>
<tr>
<th>userID</th>
<th>name</th>
<th>email</th>
</tr>
</thead>
<tbody>
{[Link]((user, ind) => {
return (<tr key={ind}>
<td>{[Link]}</td>
<td>{[Link]}</td>
<td>{[Link]}</td>
</tr>)
})}
</tbody>
</table>
)
}
}
-----------------------------------------------------
import React, { useEffect, useState } from "react";
export default function Comments() {
const [comments, setComments] = useState([]);
useEffect(() => {
fetch("[Link]
.then((response) => [Link]())
.then((result) => {
setComments(result);
});
});
return (
<>
<h1>Comment List</h1>
[Link] = {
modalIsOpen: false,
isEdit: false,
users: [],
id: "",
name: "",
email: "",
address: "",
phone: "",
};
}
myChangeHandler = (event) => {
let nam = [Link];
let val = [Link];
[Link]({ [nam]: val });
};
mySubmitHandler = (event) => {
[Link]();
let output = {};
output = {
name: [Link],
email: [Link],
phone: [Link],
address: [Link],
};
if ([Link]) {
[Link](output, [Link]);
} else {
[Link](output);
}
};
fetchEmployees = () => {
const myURL = "[Link]
[Link](myURL).then((result) => {
[Link]({ users: [Link] });
});
};
addEmployee(data) {
const myURL = "[Link]
[Link](myURL, data).then((response) => {
[Link]("Employee got added", "", "success");
[Link]();
[Link]();
});
}
};
const mySubmitHandler = function(event) {
[Link]();
addUser();
};
return (
<>
<h1 className="text-center">CRUD Example</h1>
<hr />
<button onClick={fetchUsers}>get data</button>
<div className="container">
<div className="row">
<div className="col-sm-8">
<table className="table table-bordered table-striped table-responsive">
<thead>
<tr>
<th>Name</th>
<th>email</th>
<th>phone</th>
<th>address</th>
<th>Action</th>
</tr>
</thead>
<tbody>
{[Link] > 0 ? (
[Link]((user) => (
<tr key={[Link]}>
<td>{[Link]}</td>
<td>{[Link]}</td>
<td>{[Link]}</td>
<td>{[Link]}</td>
<td>
<button className="btn btn-danger" onClick={() =>
deleteUser([Link])}>
DELETE
</button>
<button className="btn btn-secondary" onClick={() =>
editUser([Link])}>
EDIT
</button>
</td>
</tr>
))
) : (
<tr>
<td colSpan={5} className='text-center'>No data yet</td>
</tr>
)}
</tbody>
</table>
</div>
<div className="col-sm-4">
<form onSubmit={mySubmitHandler}>
Name: <input name="name" value={name}
onChange={e=>setName([Link])} /> <br /><br />
email: <input name="email" value={email}
onChange={e=>setEmail([Link])} /> <br /><br />
phone: <input name="phone" value={phone}
onChange={e=>setPhone([Link])} /> <br /><br />
address: <input name="address" value={address}
onChange={e=>setAddress([Link])} /><br />
<br />
<button className="btn btn-primary">Add Employee</button>
</form>
</div>
</div>
</div>
</>
);
}
[Link](res => {
[Link] = new Date().getTime() - [Link]
return res;
},
err => {
[Link] = new Date().getTime() - [Link]
throw err;
});
(async () => {
try {
const headers = { Accept: 'application/json', 'Accept-Encoding': 'identity' };
const githubUserName = 'abraham';
Program: graphQL
=================
1. install apollo-client and graphQL
npm install @apollo/client graphql
------------------------------------------------
import React, { useState } from "react";
[Link]
--------------
import React, { useState } from "react";
const UpdatedComponent = (OriginalComponent) => {
function CounterHOC() {
const [count, setCount] = useState(0);
const increment = () => {
setCount(count + 1);
};
return <OriginalComponent count={count} increment={increment} />;
}
return CounterHOC;
};
export default UpdatedComponent;
[Link]
---------------
import React from "react";
import CounterHOC from "./CounterHOC";
function ClickCounterWithHOC(props) {
return (
<button onClick={[Link]}> Clicked {[Link]} Times</button>
);
}
export default CounterHOC(ClickCounterWithHOC);
[Link]
--------------
import React from "react";
import CounterHOC from "./CounterHOC";
function HoverCounterWithHOC(props) {
return (
<button onMouseOver={[Link]}> Clicked {[Link]} Times</button>
);
}
export default CounterHOC(HoverCounterWithHOC);
Program- Logging
==========================
const withLogger = (WrappedComponent) => {
const WithLogger = (props) => {
useEffect(() => {
// Log data on component mount
[Link](`Component ${[Link]} mounted.`);
return () => {
// Log data on component unmount
[Link](`Component ${[Link]} unmounted.`);
};
}, []);
useEffect(() => {
// Log data on component update
[Link](`Component ${[Link]} updated.`);
});
[Link] = `withLogger(${[Link] ||
[Link]})`;
return WithLogger;
};
program:86 Routing
******************
[Link]
------
import { BrowserRouter } from 'react-router-dom';
<BrowserRouter>
<App />
</BrowserRouter>
[Link]
---------
import { Route, Routes } from "react-router";
<Routes>
<Route exact path="/" element={<Home />} />
<Route exact path="/home" element={<Home />} />
<Route exact path="/aboutus" element={<Aboutus />} />
<Route exact path="/careers" element={<Careers />} />
<Route exact path="/products" element={<Products />} />
<Route path="*" element={<NotFound />} />
</Routes>
[Link]
------
<ul class="nav navbar-nav">
<li class="active">
<Link to="/products">Product</Link>
</li>
<li>
<Link to="/greet">greet</Link>
</li>
<li>
<Link to="/http">http</Link>
</li>
<li>
<Link to="/parent">parent</Link>
</li>
</ul>
Lazy Loading
============
const ProductList = [Link](() => import("./components/list/product_list"));
<Suspense fallback={<h1>Loading...</h1>}>
<Routes>
<Route exact path="products" element={<ProductList />} />
</Routes>
</Suspense>
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
Program-89 useState with array data
************************************
import React, { useState } from 'react'
function setDefaultValues() {
setId('');
setName('');
setSal('')
}
const deleteEmp = (ind) => {
[Link](ind, 1)
setEmployees([...employees])
}
const addEmployee = (event) => {
[Link]();
let newObj = { "id": id, "name": name, "sal": sal };
setEmployees([...employees, newObj])
setDefaultValues();
}
return (
<>
<table className='table table-bordered table-striped table-responsive'>
<thead>
<tr>
<th>eid</th>
<th>name</th>
<th>sal</th>
<th>Action</th>
</tr>
</thead>
<tbody>
{[Link]((employee, ind) => {
return (
<tr>
<td>{[Link]}</td>
<td>{[Link]}</td>
<td>{[Link]}</td>
<td>
<button className='btn btn-danger' onClick={()
=> deleteEmp(ind)}>DELETE</button>
</td>
</tr>
)
})}
</tbody>
</table>
<hr />
<form onSubmit={addEmployee}>
id : <input
name="id"
type="text"
value={id}
onChange={e => setId([Link])}
/> <br /><br />
Name : <input
name="name"
type="text"
value={name}
onChange={e => setName([Link])}
/> <br /><br />
Name : <input
name="sal"
type="text"
value={sal}
onChange={e => setSal([Link])}
/> <br /><br />
</>
);
}
program-90 useEffect
********************
import React, { useState, useEffect } from 'react'
useEffect(() => {
fetch("[Link]
.then(response => [Link]())
.then(result => setUsers(result));
}, []);
return (
<div>
<table className='table table-bordered table-striped table-responsive'>
<thead>
<tr>
<th>id</th>
<th>name</th>
<th>email</th>
<th>phone</th>
</tr>
</thead>
<tbody>
{[Link]((user, ind) => {
return (
<tr>
<td>{[Link]}</td>
<td>{[Link]}</td>
<td>{[Link]}</td>
<td>{[Link]}</td>
</tr>
)
})}
</tbody>
</table>
</div>
);
}
useEffect(async () => {
const response = await fetch(url);
const data = await [Link]();
setData(data);
}, []);
return data;
}
[Link]
-------
import React, { useState, useEffect } from 'react'
import useFetch from '../customhook/fetchHook';
[Link]
---------------
import { createContext, useState } from "react";
export const ThemeContext = createContext();
export const ThemeProvider = ({ children }) => {
const [theme, setTheme] = useState('light');
const toggleTheme = () => {
setTheme((prev) => {
return prev === 'light' ? 'dark' : 'light';
})
}
return <[Link] value={{ theme, toggleTheme }}>
{children}
</[Link]>
}
3. Create Folders & Files for actions, reducers, store and components
store-->[Link]
actions-->[Link]
reducers-->[Link]
components-->[Link]
3. Create Folders & Files for actions, reducers, store and components
store-->[Link]
features/todo --> [Link]
components--> [Link] , [Link], [Link]
6. Create a Redux "slice" reducer with createSlice , Export the generated slice
reducer and action creators
import { createSlice } from '@reduxjs/toolkit';
const initialState = {
todoList: [
{ id: 1, text: "Learn React", isCompleted: false },
{ id: 2, text: "Complete Java Assignments", isCompleted: true },
]
}
// slice = reducers + action_creators
export const todoSlice = createSlice({
name: 'todo',
initialState,
reducers: {
addToDo: {
reducer: (state, action) => {
[Link]([Link]);
},
prepare: (text) => ({
payload: {
id: [Link]() * 20,
text,
completed: false,
}
})
},
deleteToDo: (state, action) => {
[Link] = [Link](todo => [Link] !==
[Link]);
return state;
},
toggleToDo: (state, action) => {
[Link] = [Link]((toDo) =>
[Link] === [Link] ? { ...toDo,
isCompleted: ![Link] } : toDo
);
return state;
}
}
})
// Action creators are generated for each case reducer function
export const { addToDo, deleteToDo, toggleToDo } = [Link]; //
Action Creators
export default [Link];
7. Read data from the store with the useSelector hook ([Link])
import { useSelector } from 'react-redux'
import ToDo from './ToDo';
import AddToDo from './AddToDo';
export default function ToDoList() {
const todoArr = useSelector((state) => [Link]);
const CompletedToDos = [Link](todo => [Link]);
return <>
<div className='col-sm-4 offset-4'>
<div className='p-3 m-3 border border-3 rounded-3'>
<h2 className='text-center'>ToDo List Using
REDUX</h2>
<hr />
<AddToDo />
<hr/>
{[Link]((todoObj, ind) => {
return <ToDo todoObj={todoObj} ind={ind} />
})}
<hr />
{[Link]}/{[Link]} are
completed
</div>
</div>
</>
}
9. [Link]
import { useDispatch } from 'react-redux'
import { deleteToDo, toggleToDo } from '../features/todo/todoSlice';
export default function ToDo({ todoObj }) {
const dispatch = useDispatch();
const deleteMyTodo = (id) => {
const actionObj = deleteToDo(id);
dispatch(actionObj)
}
const toggleMyTodo = (id) => {
const actionObj = toggleToDo(id);
dispatch(actionObj)
}
return <>
<li>
<span style={{ textDecoration: [Link] ? 'line-
through' : 'none' }}>
{[Link]}
</span>
<button onClick={() =>
{ deleteMyTodo([Link]) }}>DELETE</button>
<button onClick={() =>
{ toggleMyTodo([Link]) }}>TOGGLE</button>
</li>
</>
}
10. [Link]
import React, { useRef } from 'react'
import { useDispatch } from 'react-redux';
import { addToDo } from '../features/todo/todoSlice';
export default function AddToDo() {
const dispatch = useDispatch();
const myRef1 = useRef();
const addNewToDo = () => {
const actionObj = addToDo([Link]);
dispatch(actionObj);
[Link] = '';
};
return <>
<input ref={myRef1} />
<button onClick={addNewToDo}>Add New ToDo</button>
</>
}
const initialTodos = [
{ id: 1, title: "Todo 1", complete: false },
{ id: 2, title: "Todo 2", complete: true },
];
const reducer = (state, action) => {
switch ([Link]) {
case "ADD":
return [...state, [Link]];
case "DELETE":
return [Link]((todo) => [Link] !== [Link]);
case "TOGGLE":
return [Link]((todo) => {
if ([Link] === [Link]) {
return { ...todo, complete: ![Link] };
} else {
return todo;
}
});
default:
return state;
}
};
let nextTodoId = 3;
export default function UseReducerDemo() {
const [todos, dispatch] = useReducer(reducer, initialTodos);
const myref1 = useRef();
return (
<>
<Todos todos={todos} addTodo={addTodo} />
<hr />
<div>
Count: {count}
<button onClick={increment}>+</button>
</div>
</>
);
};
----------------------------------------------
import { memo } from "react";
const Todos = ({ todos, addTodo }) => {
[Link]("child render");
return (
<>
<h2>My Todos</h2>
{[Link]((todo, index) => {
return <p key={index}>{todo}</p>;
})}
<button onClick={addTodo}>Add Todo</button>
</>
);
};
export default memo(Todos);
function Test() {
return (
<div>
<p>
<b>
This is an example of error boundaries in React 16.
<br /><br />
Click on the numbers to increase the counters.
<br />
The counter is programmed to throw when it reaches 5. This simulates a
JavaScript error in a component.
</b>
</p>
<hr />
<ErrorBoundary>
<p>These two counters are inside the same error boundary. If one crashes,
the error boundary will replace both of them.</p>
<BuggyCounter />
<BuggyCounter />
</ErrorBoundary>
<hr />
<p>These two counters are each inside of their own error boundary. So if one
crashes, the other is not affected.</p>
<ErrorBoundary><BuggyCounter /></ErrorBoundary>
<ErrorBoundary><BuggyCounter /></ErrorBoundary>
</div>
);
}
Program-100 Portals
*************************
1. add target div in [Link]
<div id="modal-root"></div> <!--Root Element for Portal-->