- App.js
import { useReducer, useState } from "react";
import Students from "./Students";
const defaultStudentState = {
count: 1,
students: [
{
id: Math.floor(Math.random() * 10000),
name: "건디",
checked: false,
},
],
};
const studentReducer = (state, action) => {
if (action.type === "ADD") {
const newStudent = {
id: Math.floor(Math.random() * 10000),
name: action.payload,
checked: false,
};
return {
count: state.count + 1,
students: [...state.students, newStudent],
};
}
if (action.type === "REMOVE") {
return {
count: state.count - 1,
students: state.students.filter(
(student) => student.id !== action.payload
),
};
}
if (action.type === "TOGGLE") {
return {
count: state.count,
students: state.students.map((student) => {
if (student.id === action.payload) {
return { ...student, checked: !student.checked };
}
return student;
}),
};
}
return defaultStudentState;
};
function App() {
const [studentState, dispatchStudentAction] = useReducer(
studentReducer,
defaultStudentState
);
const [name, setName] = useState("");
const nameHandler = (e) => {
setName(e.target.value);
};
const dispatchStudentAddHandler = () => {
dispatchStudentAction({ type: "ADD", payload: name });
};
const dispatchStudentRemoveHandler = (id) => {
dispatchStudentAction({ type: "REMOVE", payload: id });
};
const dispatchStudentToggleHanlder = (id) => {
dispatchStudentAction({ type: "TOGGLE", payload: id });
};
return (
<>
<h1>출석부</h1>
<p>총 학생 수 : {studentState.count}</p>
<input
type={"text"}
placeholder="이름을 입력하세요"
value={name}
onChange={nameHandler}
></input>
<button onClick={dispatchStudentAddHandler}>추가</button>
{studentState.students.map((student) => {
return (
<Students
dispatchStudentRemoveHandler={
() => dispatchStudentRemoveHandler(student.id)
}
id={student.id}
key={student.id}
name={student.name}
checked={student.checked}
dispatchStudentToggleHanlder={() => {
dispatchStudentToggleHanlder(student.id);
}}
/>
);
})}
</>
);
}
export default App;
- Students.js
import React from "react";
function Students(props) {
return (
<div>
<span
style={{
textDecoration: props.checked ? "line-through" : "none",
color: props.checked ? "gray" : "black",
}}
onClick={props.dispatchStudentToggleHanlder}
>
{props.name}
</span>
<button onClick={props.dispatchStudentRemoveHandler}>삭제</button>
</div>
);
}
export default Students;