Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 3

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

import './App.css';
import { EmployeeData } from './EmployeeData';

function App() {
const [data, setData] = useState([]);
const [firstName, setFirstName] = useState('');
const [lastName, setLastName] = useState('');
const [name, setName] = useState('');
const [id, setId] = useState(null); // Track the id of the item being edited

useEffect(() => {
setData(EmployeeData);
}, []);

const handleEdit = (id) => {


const item = data.find(item => item.id === id);
setFirstName(item.firstName);
setLastName(item.lastName);
setName(item.name);
setId(item.id);
};

const handleDelete = (id) => {


if (id > 0) {
if (window.confirm('Are you sure to delete this item?')) {
const updatedData = data.filter(item => item.id !== id);
setData(updatedData);
}
}
};

const handleSave = () => {


if (id === null) {
// Add new item
const newId = data.length ? data[data.length - 1].id + 1 : 1;
const newData = {
id: newId,
firstName: firstName,
lastName: lastName,
name: name
};
setData([...data, newData]);
} else {
// Update existing item
const updatedData = data.map(item =>
item.id === id ? { id, firstName, lastName, name } : item
);
setData(updatedData);
}
handleClear();
};

const handleClear = () => {


setFirstName('');
setLastName('');
setName('');
setId(null); // Clear the id to indicate no item is being edited
};
return (
<div className="App">
<div style={{ display: 'flex', justifyContent: 'center', flexDirection:
'column', alignItems: 'center' }}>
<div>
<label>
First Name:
<input type="text" placeholder="Enter First name" value={firstName}
onChange={(e) => setFirstName(e.target.value)} />
</label>
</div>
<div>
<label>
Last Name:
<input type="text" placeholder="Enter Last name" value={lastName}
onChange={(e) => setLastName(e.target.value)} />
</label>
</div>
<div>
<label>
Name:
<input type="text" placeholder="Enter name" value={name} onChange={(e)
=> setName(e.target.value)} />
</label>
</div>
<div>
<button className="btn btn-primary"
onClick={handleSave}>Save</button>&nbsp;
<button className="btn btn-danger" onClick={handleClear}>Clear</button>
</div>
</div>

<table className="table table-hover">


<thead>
<tr>
<th>Sr. No</th>
<th>First Name</th>
<th>Last Name</th>
<th>Name</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{data.map((item, index) => (
<tr key={index}>
<td>{index + 1}</td>
<td>{item.firstName}</td>
<td>{item.lastName}</td>
<td>{item.name}</td>
<td>
<button className="btn btn-primary" onClick={() =>
handleEdit(item.id)}>Edit</button>&nbsp;
<button className="btn btn-danger" onClick={() =>
handleDelete(item.id)}>Delete</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
);
}

export default App;

You might also like