React Programs
React Programs
************************************************
<html>
<head>
    <script crossorigin
src="https://unpkg.com/react@18/umd/react.development.js"></script>
    <script crossorigin src="https://unpkg.com/react-dom@18/umd/react-
dom.development.js"></script>
</head>
<body>at
    <div id="example"></div>
    <script>
         const reactEle = React.createElement('h1', {}, 'My First React App');
             const domEle = document.getElementById('example');
         const root = ReactDOM.createRoot(domEle);
         root.render(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 React.Component {
    render() {
        return (
            <React.Fragment>
                 <div>I am an element!</div>
                 <button>I am another element</button>
            </React.Fragment>
        );
    }
}
export default Header;
program-11 : CSS
****************
import React from 'react';
class App extends React.Component {
   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;
-------------
DashedBox2.css
--------------
.error{
      background-color:yellow;
}
-------------
import React from 'react';
import styles from './DashedBox.module.css';
import './DashedBox2.css';
-------------------(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={emp.eId}>
                     <td>{emp.eId}</td>
                     <td>{emp.name}</td>
                     <td>{emp.sal}</td>
                 </tr>
            );
            empRows.push(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 React.Component {
    render() {
        let user = { name: 'sachin', age: 35 }
        return (
            <div>
                 This is Parent Component
                 <Child name={user.name} age={user.age} />
            </div>
        );
    }
}
export default Parent;
-------------------
import React from 'react';
class Child extends React.Component {
    render() {
        return (
            <div>
                 <h2>This is child component</h2>
                 <h2>{this.props.name}--{this.props.age}</h2>
            </div>
        );
    }
}
export default Child;
Program-27 propTypes
*******************
import React from 'react';
import { PropTypes } from 'prop-types';
class Student extends React.Component {
    render() {
      return (
         <div>
           <p>Student Name: {this.props.name}</p>
           <p>Age: {this.props.age}</p>
         </div>
      );
    }
}
Student.propTypes = {
   name: PropTypes.string.isRequired,
   age: PropTypes.number
};
export default Student;
Program-29: props.children
**************************
import React from 'react';
import Greet from '../greet/greet';
class Content extends React.Component {
    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 React.Component {
    render() {
        return (
            <h2>
                 This is Greet Component
                 {this.props.children}
            </h2>
        );
    }
}
export default Greet;
Program-31: States
******************
class Counter extends React.Component {
    constructor(props) {
      super(props);
      this.state = {count: 0 };
  }
  increment = () => {
     this.setState({count: this.state.count + 1});
  }
  render() {
      return (
         <div>
           <div>count:{this.state.count}</div>
           <button onClick={this.increment}>click!</button>
         </div>
      );
  }
};
Program-35 Show/Hide
*********************
import React from 'react';
class MyClass extends React.Component {
    constructor(props) {
        super(props);
        this.state = { flag: true };
    }
    toggleFlag = () => {
        this.setState({ flag: !this.state.flag });
    }
    render() {
        return (
             <div>
                 {this.state.flag ? <div>Hellllllo</div> : null}
                 <button onClick={this.toggleFlag}>
                     {this.state.flag ? '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={this.state.flag ? 'password' : 'text'} />
                 <button onClick={this.togglePassword}>{this.state.flag ? '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 {this.state.total}</h2>
                  <button onClick={this.addition}>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(+e.target.value);
                 }} />
                 <input type="number" onKeyUp={(e) => {
                     setnum2(+e.target.value);
                 }} />
    if (folderInfo.isFolder) { // if folder
        return <div>
            <span onClick={() => setExpand(!expand)} style={{ cursor: 'pointer' }}>
                 📁
                 {folderInfo.name}
                 <br />
            </span>
            <div
                 style={{ display: expand ? "block" : "none", paddingLeft: "20px" }}
            >
                 {folderInfo.items.map((subfolderInfo, ind) => (
                     <Folder folderInfo={subfolderInfo} key={ind} />
                 ))}
            </div>
        </div>
    } else { // if file
        return <span>
            🏢
            {folderInfo.name} <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>
                 {filteredEmployees.map((emp, ind) => (
                   <tr key={ind}>
                      <td>{emp.number}</td>
                      <td>{emp.name}</td>
                      <td>{emp.position}</td>
                   </tr>
                 ))}
               </tbody>
             </table>
          }
       </>
    );
}
Program-42   Pagination
************************
import React, { useState } from "react";
import productsArr from "./Products.json";
import ReactPaginate from "react-paginate";
import "./ProductsPagination.css";
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">
          {filteredProducts.map((product) => (
             <div className="col-sm-3" key={product.id}>
               <div className="card text-center">
                 <img
                    src={product.image}
                    className="card-img-top"
                    alt="..."
                    style={{ height: "200px" }}
                 />
                 <div className="card-body">
                    <h5 className="card-title">{product.category}</h5>
                    <p className="card-text">{product.title}</p>
                    <p
                       className="card-text"
                       style={{ height: "200px", overflow: "scroll" }}
                    >
                       {product.description}
                    </p>
                    <p className="card-text"> {product.price}</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"
        />
      </>
    );
}
ProductsPagination.css
=======================
.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>
                     {this.state.employees.map((emp, ind) => (
                          <tr key={emp.eId}>
                              <td>{ind}</td>
                              <td>{emp.eId}</td>
                              <td>{emp.name}</td>
                              <td>{emp.sal}</td>
                              <td>
                                   <button onClick={() =>
this.deleteRow(ind)}>Delete</button>
                                   <button onClick={() =>
this.viewRow(emp)}>View</button>
                              </td>
                          </tr>
                     ))}
                 </table>
                 Emp Id:
                     <input onKeyUp={this.updateId}></input> <br></br><br></br>
                 Name:
                     <input onKeyUp={this.updateName}></input> <br></br><br></br>
                 Salary:
                     <input onKeyUp={this.updateSal}></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) {
  console.log("demo-2 render called");
  return (
     <div>
       Demo2
       {props.cars.map((car) => {
         return <li>{car}</li>;
       })}
     </div>
  );
}
export default React.memo(Demo2);
program-51 componentDidMount
******************************
class Header extends React.Component {
  constructor(props) {
    super(props);
    this.state = {favoritecolor: "red"};
  }
  componentDidMount() {
    setTimeout(() => {
       this.setState({favoritecolor: "yellow"})
    }, 1000)
  }
  render() {
    return (
       <h1>My Favorite Color is {this.state.favoritecolor}</h1>
    );
  }
}
Program-52   shouldComponentUpdate
**********************************
class Header extends React.Component {
    constructor(props) {
      super(props);
      this.state = {favoritecolor: "red"};
    }
    shouldComponentUpdate() {
      return false;
    }
    changeColor = () => {
      this.setState({favoritecolor: "blue"});
    }
    render() {
      return (
         <div>
         <h1>My Favorite Color is {this.state.favoritecolor}</h1>
         <button type="button" onClick={this.changeColor}>Change color</button>
         </div>
      );
    }
}
Program-53    getSnapshotBeforeUpdate
************************************
class Header extends React.Component {
  constructor(props) {
    super(props);
    this.state = {favoritecolor: "red"};
  }
  componentDidMount() {
    setTimeout(() => {
       this.setState({favoritecolor: "yellow"})
    }, 1000)
  }
  getSnapshotBeforeUpdate(prevProps, prevState) {
    document.getElementById("div1").innerHTML =
    "Before the update, the favorite was " + prevState.favoritecolor;
  }
  componentDidUpdate() {
    document.getElementById("div2").innerHTML =
    "The updated favorite is " + this.state.favoritecolor;
  }
  render() {
    return (
       <div>
         <h1>My Favorite Color is {this.state.favoritecolor}</h1>
         <div id="div1"></div>
         <div id="div2"></div>
       </div>
    );
  }
}
program-54   componentDidUpdate
*********************************
class Header extends React.Component {
    constructor(props) {
      super(props);
      this.state = {favoritecolor: "red"};
    }
    componentDidMount() {
      setTimeout(() => {
         this.setState({favoritecolor: "yellow"})
      }, 1000)
    }
    componentDidUpdate() {
      document.getElementById("mydiv").innerHTML =
      "The updated favorite is " + this.state.favoritecolor;
    }
    render() {
      return (
         <div>
         <h1>My Favorite Color is {this.state.favoritecolor}</h1>
         <div id="mydiv"></div>
         </div>
      );
    }
}
program-60 (componentWillUnmount)
*********************************
class Container extends React.Component {
  constructor(props) {
    super(props);
    this.state = {show: true};
  }
  delHeader = () => {
    this.setState({show: false});
  }
  render() {
    let myheader;
    if (this.state.show) {
       myheader = <Child />;
    };
    return (
       <div>
       {myheader}
       <button type="button" onClick={this.delHeader}>Delete Header</button>
       </div>
    );
  }
}
    useEffect(() => {
       console.log("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(e.target.value)}
            placeholder="Type to search"
         />
         <p>Showing {filtered.length} results</p>
         <ul>
            {filtered.slice(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(e.target.value)} />
         Last Name:
         <input name="lname" value={lname} onChange={(e) =>
setLname(e.target.value)} />
         <br />
         <br />
         <button>submit</button>
       </form>
     </>
  );
}
  return (
    <>
       <form onSubmit={submitHandler}>
         First Name:
         <input
            name="fname"
            value={user.fname}
            onChange={(e) => setUser({ ...user, fname: e.target.value })}
         />
         Last Name:
         <input
            name="lname"
            value={user.lname}
            onChange={(e) => setUser({ ...user, lname: e.target.value })}
         />
         <br />
         <br />
         state data: {user.fname + " " + user.lname}
         <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>
                              {JSON.stringify(formData,null,4)}
                          </pre>
                      </div>
                  </div>
              </div>
          </div>
    </>
}
const initialFormValue = {
    name: "", email: "", password: "", confirmPassword: "",
    gender: "", role: "", skills: [], acceptTerms: false
}
const skillsList = ["JavaScript", "React", "Node.js", "Python"];
const validationSchema = Yup.object({
    name: Yup.string().required("Name is required"),
    email: Yup.string()
        .email("Invalid email address")
        .required("Email is required"),
    password: Yup.string()
        .min(6, "Password must be at least 6 characters")
        .required("Password is required"),
    confirmPassword: Yup.string()
        .oneOf([Yup.ref("password"), null], "Passwords must match")
        .required("Confirm password is required"),
    gender: Yup.string().required("Gender is required"),
    role: Yup.string().required("Role is required"),
    skills: Yup.array().min(1, "Select at least one skill"),
    acceptTerms: Yup.boolean().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>
                                {skillsList.map((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>{JSON.stringify(formData, null, 2)}</pre>
                    </div>
                )}
            </div>
        </div>
    </>
}
        if (this.state.username.length < 5) {
            err1 = <strong>Your name mustcontain 5 chars</strong>;
        }
        if (this.state.age !== "" && !Number(this.state.age)) {
            err2 = <strong>Your age must be a number</strong>;
        }
        this.setState({ nameErrorMsg: err1, ageErrorMsg: err2 });
        //alert("You are submitting " + this.state.username + " " +
this.state.age);
    }
    render() {
        return (
            <form onSubmit={this.mySubmitHandler}>
                 <h1>Hello {this.state.username} {this.state.age}</h1>
                 <p>Enter your name:</p>
                 <input
                     type='text'
                     name='username'
                     onChange={this.myChangeHandler}
                 />
                 {this.state.nameErrorMsg}
                 <br></br>
                 <input type="submit" />
             </form>
        );
    }
}
export default MyForm;
Program-77 DropDown
********************
class MyForm extends React.Component {
  import React, { Component } from 'react'
    fetchUsers = () => {
        const myURL = 'https://jsonplaceholder.typicode.com/users';
        fetch(myURL)
            .then((response) => response.json())
            .then((data) => {
                console.log(data);
                this.setState({ 'users': data })
            });
    }
    componentDidMount() {
        this.fetchUsers();
    }
    render() {
        return (
            <table className='table table-bordered table-striped'>
                 <thead>
                     <tr>
                          <th>userID</th>
                          <th>name</th>
                          <th>email</th>
                     </tr>
                 </thead>
                 <tbody>
                     {this.state.users.map((user, ind) => {
                          return (<tr key={ind}>
                              <td>{user.id}</td>
                              <td>{user.name}</td>
                              <td>{user.email}</td>
                          </tr>)
                     })}
                 </tbody>
            </table>
        )
    }
}
-----------------------------------------------------
import React, { useEffect, useState } from "react";
export default function Comments() {
  const [comments, setComments] = useState([]);
  useEffect(() => {
    fetch("https://jsonplaceholder.typicode.com/comments")
       .then((response) => response.json())
       .then((result) => {
         setComments(result);
       });
  });
  return (
    <>
       <h1>Comment List</h1>
      this.state = {
         modalIsOpen: false,
         isEdit: false,
         users: [],
         id: "",
         name: "",
         email: "",
         address: "",
         phone: "",
      };
    }
    myChangeHandler = (event) => {
       let nam = event.target.name;
       let val = event.target.value;
       this.setState({ [nam]: val });
    };
mySubmitHandler = (event) => {
   event.preventDefault();
   let output = {};
   output = {
      name: this.state.name,
      email: this.state.email,
      phone: this.state.phone,
      address: this.state.address,
   };
   if (this.state.isEdit) {
      this.updateEmployees(output, this.state.id);
   } else {
      this.addEmployee(output);
   }
};
fetchEmployees = () => {
   const myURL = "http://localhost:4000/users";
   axios.get(myURL).then((result) => {
      this.setState({ users: result.data });
   });
};
addEmployee(data) {
  const myURL = "http://localhost:4000/users";
  axios.post(myURL, data).then((response) => {
    Swal.fire("Employee got added", "", "success");
    this.closeModal();
    this.fetchEmployees();
  });
}
  };
  const mySubmitHandler = function(event) {
     event.preventDefault();
     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>
                  {users.length > 0 ? (
                     users.map((user) => (
                        <tr key={user.id}>
                          <td>{user.name}</td>
                          <td>{user.email}</td>
                          <td>{user.phone}</td>
                          <td>{user.address}</td>
                          <td>
                            <button className="btn btn-danger" onClick={() =>
deleteUser(user.id)}>
                               DELETE
                            </button>  
                            <button className="btn btn-secondary" onClick={() =>
editUser(user.id)}>
                               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(e.target.value)} /> <br /><br />
                email: <input name="email" value={email}
onChange={e=>setEmail(e.target.value)} /> <br /><br />
                phone: <input name="phone" value={phone}
onChange={e=>setPhone(e.target.value)} /> <br /><br />
                address: <input name="address" value={address}
onChange={e=>setAddress(e.target.value)} /><br />
                <br />
                <button className="btn btn-primary">Add Employee</button>
              </form>
           </div>
         </div>
       </div>
     </>
  );
}
axios.interceptors.response.use(res => {
   res.durationInMs = new Date().getTime() - res.config.meta.requestStartedAt
   return res;
},
err => {
   err.durationInMs = new Date().getTime() - err.config.meta.requestStartedAt
   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";
withcounter.js
--------------
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;
clickCounter.js
---------------
import React from "react";
import CounterHOC from "./CounterHOC";
function ClickCounterWithHOC(props) {
  return (
     <button onClick={props.increment}> Clicked {props.count} Times</button>
  );
}
export default CounterHOC(ClickCounterWithHOC);
hovercounter.js
--------------
import React from "react";
import CounterHOC from "./CounterHOC";
function HoverCounterWithHOC(props) {
  return (
     <button onMouseOver={props.increment}> Clicked {props.count} Times</button>
  );
}
export default CounterHOC(HoverCounterWithHOC);
Program- Logging
==========================
const withLogger = (WrappedComponent) => {
  const WithLogger = (props) => {
    useEffect(() => {
      // Log data on component mount
      console.log(`Component ${WrappedComponent.name} mounted.`);
      return () => {
         // Log data on component unmount
         console.log(`Component ${WrappedComponent.name} unmounted.`);
      };
    }, []);
    useEffect(() => {
      // Log data on component update
      console.log(`Component ${WrappedComponent.name} updated.`);
    });
   WithLogger.displayName = `withLogger(${WrappedComponent.displayName ||
WrappedComponent.name})`;
   return WithLogger;
};
program:86 Routing
******************
index.js
------
import { BrowserRouter } from 'react-router-dom';
   <BrowserRouter>
         <App />
   </BrowserRouter>
center.js
---------
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>
nav.js
------
<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 = React.lazy(() => 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) => {
        employees.splice(ind, 1)
        setEmployees([...employees])
    }
    const addEmployee = (event) => {
        event.preventDefault();
        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>
                    {employees.map((employee, ind) => {
                         return (
                             <tr>
                                  <td>{employee.id}</td>
                                  <td>{employee.name}</td>
                                  <td>{employee.sal}</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(e.target.value)}
                   /> <br /><br />
                   Name : <input
                       name="name"
                       type="text"
                       value={name}
                       onChange={e => setName(e.target.value)}
                   /> <br /><br />
                   Name : <input
                       name="sal"
                       type="text"
                       value={sal}
                       onChange={e => setSal(e.target.value)}
                   /> <br /><br />
         </>
    );
}
program-90 useEffect
********************
import React, { useState, useEffect } from 'react'
    useEffect(() => {
        fetch("https://jsonplaceholder.typicode.com/users")
            .then(response => response.json())
            .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>
                        {users.map((user, ind) => {
                            return (
                                <tr>
                                     <td>{user.id}</td>
                                     <td>{user.name}</td>
                                     <td>{user.email}</td>
                                     <td>{user.phone}</td>
                                </tr>
                            )
                        })}
                   </tbody>
               </table>
           </div>
      );
}
    useEffect(async () => {
      const response = await fetch(url);
      const data = await response.json();
      setData(data);
    }, []);
    return data;
}
test.js
-------
import React, { useState, useEffect } from 'react'
import useFetch from '../customhook/fetchHook';
ThemeContext.js
---------------
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 <ThemeContext.Provider value={{ theme, toggleTheme }}>
        {children}
    </ThemeContext.Provider>
}
3. Create Folders & Files for actions, reducers, store and components
    store-->store.js
      actions-->actions.js
      reducers-->reducers.js
      components-->counter.js
3. Create Folders & Files for actions, reducers, store and components
     store-->store.js
       features/todo --> todoSlice.js
       components--> ToDoList.js , ToDo.js, AddToDo.js
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) => {
                              state.todoList.push(action.payload);
                        },
                        prepare: (text) => ({
                              payload: {
                                    id: Math.random() * 20,
                                    text,
                                    completed: false,
                              }
                        })
                  },
                  deleteToDo: (state, action) => {
                        state.todoList = state.todoList.filter(todo => todo.id !==
action.payload);
                        return state;
                  },
                  toggleToDo: (state, action) => {
                        state.todoList = state.todoList.map((toDo) =>
                              toDo.id === action.payload ? { ...toDo,
isCompleted: !toDo.isCompleted } : toDo
                        );
                        return state;
                  }
            }
      })
      // Action creators are generated for each case reducer function
      export const { addToDo, deleteToDo, toggleToDo } = todoSlice.actions; //
Action Creators
      export default todoSlice.reducer;
7. Read data from the store with the useSelector hook (ToDoList.js)
    import { useSelector } from 'react-redux'
      import ToDo from './ToDo';
      import AddToDo from './AddToDo';
      export default function ToDoList() {
            const todoArr = useSelector((state) => state.todoReducer.todoList);
            const CompletedToDos = todoArr.filter(todo => todo.isCompleted);
            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/>
                              {todoArr.map((todoObj, ind) => {
                                    return <ToDo todoObj={todoObj} ind={ind} />
                              })}
                              <hr />
                              {CompletedToDos.length}/{todoArr.length} are
completed
                        </div>
                  </div>
            </>
      }
9. ToDo.js
      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: todoObj.isCompleted ? 'line-
through' : 'none' }}>
                              {todoObj.text}
                        </span>  
                        <button onClick={() =>
{ deleteMyTodo(todoObj.id) }}>DELETE</button>  
                        <button onClick={() =>
{ toggleMyTodo(todoObj.id) }}>TOGGLE</button>  
                  </li>
            </>
      }
10. AddToDo.js
      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(myRef1.current.value);
                  dispatch(actionObj);
                  myRef1.current.value = '';
            };
            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 (action.type) {
     case "ADD":
       return [...state, action.payload];
     case "DELETE":
       return state.filter((todo) => todo.id !== action.id);
     case "TOGGLE":
       return state.map((todo) => {
         if (todo.id === action.id) {
           return { ...todo, complete: !todo.complete };
         } 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 }) => {
   console.log("child render");
   return (
      <>
         <h2>My Todos</h2>
         {todos.map((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 index.html
   <div id="modal-root"></div> <!--Root Element for Portal-->