Thursday 23 November 2023

CRUD operation using React

We will see below CRUD operation in step by step

--To create react App
>npx create-react-app react-crud-operation
>cd react-crud-operation
>code .
>npm start

--To create json-server
>npm install -g json-server
>json-server --watch src/db.json -p 8000

On click Add/ Edit button 
Folder Structure
Need to install some supporting dependencies as axios, bootstrap
--Install Bootstrap
>npm install --save bootstrap
---then import in index.js file

--Shortcut to create function component
---rfce

I. db.json file and below are code snippets
{
  "employees": [
    {
      "id": 1,
      "name": "Subs",
      "salary": 45000,
      "designation": "Senior Software Engineer",
      "skills": "Dot Net"
    },
]
}

II. api.js file and below are code snippets
{
  "name": "react-crud-operation2",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.17.0",
    "@testing-library/react": "^13.4.0",
    "@testing-library/user-event": "^13.5.0",
    "axios": "^1.5.0",
    "bootstrap": "^5.3.1",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-scripts": "5.0.1",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

III. App.js file and below are code snippets
import logo from './logo.svg';
import './App.css';
import Table from './Table';
import { useEffect, useState } from 'react';
import { getEmployee,deleteEmployee,addEmployee,updateEmployee } from './api';
import Form from './Form';

function App() {

  const [employees,setEmployees]=useState([]);
  const [openForm,setOpenForm]=useState(false);
  const [initialForm,setForm]=useState({name:'',salary:'',designation:'',skills:''});
  const [edit,setEdit]=useState(false);

  useEffect(
    ()=>{
      getEmployees()
    },[]
  )

  let getEmployees=async ()=>{
    let res=await getEmployee();
    setEmployees(res.data);
    console.log(res.data);
  }

  let delEmployee=async (id)=>{
   await deleteEmployee(id);
   getEmployees();
  }

  let showForm=()=>{
    setOpenForm(true);
    setEdit(false);
    setForm({});
  }

  let closeForm=()=>{
    setOpenForm(false);
  }

 let editEmployee=async (data)=>{
  setForm(data);
  setOpenForm(true);
  setEdit(true);
 }

 let saveEmployee=async (data)=>{

  if(edit)
    await updateEmployee(data.id,data);
  else
    await addEmployee(data);
  getEmployees();
  setOpenForm(false);
 }

  return (
    <div className="wrapper m-5 w-50">
    <h2>React CRUD Operation Test</h2>
    <button className='btn btn-primary' onClick={()=>{showForm()}} >Add Emp</button>
    <Table employees={employees} deleteemp={delEmployee} editPopUp={editEmployee}></Table>
    {
      openForm && <Form close={closeForm} data={initialForm} saveemp={saveEmployee} ></Form>
    }
   
    </div>
   
  );
}

export default App;

IV. Form.js file and below are code snippets
import React,{useState} from 'react'

function Form(props) {

    const [emp,setEmp]= useState(props.data);

    let changeFormData=(e)=>{
        const {name,value}=e.target;
        setEmp({...emp,[name]:value});
    }

  return (
    <div className='form-overlay'>
    <form>
        <div className='form-group'>
            <label>Name</label>
            <input className='form-control mt-1' value={emp.name} onChange={changeFormData} type="text" name='name'/>
        </div>
        <div className='form-group'>
            <label>Salary</label>
            <input className='form-control mt-1' value={emp.salary} onChange={changeFormData} type="number" name="salary"/>
        </div>
        <div className='form-group'>
            <label>Designation</label>
            <input className='form-control mt-1' value={emp.designation} onChange={changeFormData} type="text" name="designation"/>
        </div>
        <div className='form-group'>
            <label>Skills</label>
            <input className='form-control mt-1' value={emp.skills} onChange={changeFormData} type="text" name="skills"/>
        </div>
        <button className='btn btn-success' onClick={(e)=>
            {
                props.saveemp(emp);
                e.preventDefault();
            }} >Save</button>
        <button className='btn btn-danger' onClick={(e)=>
        {
                props.close();
                e.preventDefault();
        }} >Cancel</button>
    </form>
    </div>
  )
}

export default Form

V. Table.js file and below are code snippets
import React from 'react'

function Table(props) {
  return (
    <table className='table'>
        <thead>
        <tr>
            <th>Id</th>
            <th>Name</th>
            <th>Salary</th>
            <th>Designation</th>
            <th>Skill</th>
        </tr>
        </thead>
        <tbody>
                {
                    props.employees.map(
                        (data)=>
                        <tr key={data.id}>
                        <td>{data.id}</td>
                        <td>{data.name}</td>
                        <td>{data.salary}</td>
                        <td>{data.designation}</td>
                        <td>{data.skills}</td>
                        <td>
                            <button className='btn btn-primary' onClick={()=>{props.editPopUp(data)}}  >Edit</button>
                            <button className='btn btn-danger' onClick={()=>{props.deleteemp(data.id)}}>Delete</button>
                        </td>
                        </tr>
                    )
                }
        </tbody>
    </table>
  )
}

export default Table

VI. index.js file and below are code snippets
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import 'bootstrap/dist/css/bootstrap.css';

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

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();



 



No comments:

Post a Comment