import { useState } from "react";
const StudentList = () => {
const [studentList, setStudentList] = useState([
{ id: 1, firstName: "first001", lastName: "Last001" },
{ id: 2, firstName: "first002", lastName: "last002" },
{ id: 3, firstName: "first003", lastName: "last003" },
{ id: 4, firstName: "first004", lastName: "last004" },
{ id: 5, firstName: "first005", lastName: "last005" },
]);
const [showModal, setShowModal] = useState(false);
const [currentStudent, setCurrentStudent] = useState(null);
const handleAdd = () => {
const newStudent = { id: studentList.length + 1, firstName: "first006", lastName: "last006" };
setStudentList((prevList) => [...prevList, newStudent]);
};
const onBeginEdit = (student) => {
setCurrentStudent(student);
setShowModal(true);
};
const onCompleteEdit = (updatedStudent) => {
setStudentList((prevList) =>
prevList.map((student) =>
student.id === updatedStudent.id ? updatedStudent : student
)
);
setShowModal(false);
};
const onControlChange = (e) => {
const { name, value } = e.target;
setCurrentStudent((prevStudent) => ({
...prevStudent,
[name]: value,
}));
};
return (
<>
<button onClick={handleAdd}>Add New</button>
<table border="1px solid black">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{studentList.map((student) => (
<tr key={student.id}>
<td>{student.firstName}</td>
<td>{student.lastName}</td>
<td>
<button onClick={() => onBeginEdit(student)}>Edit</button>
</td>
</tr>
))}
</tbody>
</table>
{showModal && currentStudent && (
<div>
<form
onSubmit={(e) => {
e.preventDefault();
onCompleteEdit(currentStudent);
}}
>
<label>First Name</label>
<input
type="text"
name="firstName"
value={currentStudent.firstName}
onChange={onControlChange}
/>
<label>Last Name</label>
<input
type="text"
name="lastName"
value={currentStudent.lastName}
onChange={onControlChange}
/>
<button type="submit">Save</button>
</form>
</div>
)}
</>
);
};
export default StudentList;
No comments:
Post a Comment