import { useState } from "react";
const TodolistPage = () => {
const [todoText, setTodoText] = useState("");
const [todoList, setTodoList] = useState([]);
const [updateTarget, setUpdateTarget] = useState({ id: 0, text: "" });
const handletoChange = (e) => {
setTodoText(e.target.value);
};
const handletoSubmit = (e) => {
if (todoText === "") {
alert("Write to do!");
} else {
const tempTodoList = todoList;
setTodoList([
...tempTodoList,
{
id:
tempTodoList.length !== 0
? tempTodoList[tempTodoList.length - 1].id + 1
: 1,
text: todoText,
},
]);
setTodoText("");
}
};
const handleDeleteTodo = (e) => {
const targetId = Number(e.target.id);
const tempTodoList = todoList.filter((todo) => todo.id !== targetId);
setTodoList(tempTodoList);
};
const handleUpdateTodo = (e) => {
const targetId = Number(e.target.id);
const targetObj = todoList.find((todo) => todo.id === targetId);
setUpdateTarget(targetObj);
};
const handleChangeUpdate = (e) => {
setUpdateTarget((prev) => ({ id: prev.id, text: e.target.value }));
};
const handleSubmitUpdate = (e) => {
const tempTodoList = todoList;
const updatedTodoList = tempTodoList.map((todo) => {
if (todo.id === updateTarget.id) {
return { id: todo.id, text: updateTarget.text };
}
return todo;
});
setTodoList(updatedTodoList);
setUpdateTarget({ id: 0, text: "" });
};
return (
<div>
<h2>Todo List</h2>
<ul>
{todoList.map((todo) => {
return updateTarget.id !== todo.id ? (
<li key={`${todo.id}`}>
{todo.text}
<button id={todo.id} onClick={handleDeleteTodo}>
x
</button>
<button id={todo.id} onClick={handleUpdateTodo}>
수정
</button>
</li>
) : (
<li key={`${todo.id}`}>
<input value={updateTarget.text} onChange={handleChangeUpdate} />
<button onClick={handleSubmitUpdate}>완료</button>
</li>
);
})}
</ul>
<input
type="text"
value={todoText}
placeholder="할 일을 입력해주세요"
onChange={handletoChange}
></input>
<button onClick={handletoSubmit}>확인</button>
</div>
);
};
export default TodolistPage;
update 기능을 추가하기 위해 delete 기능과 마찬가지로 무엇을 수정할지 targeting 하고 list에서 input 화면으로 바뀌는 기능을 추가한다. 이 기능을 위해선 삼항 연산자를 통해 수정이 클릭되지 않았을시 updateTarget.id !== todo.id
.map
을 돌려 기존과 같이 list를 작성하고 클릭되었을 시 input으로 바뀐다. targeting을 위해 수정할 state를 객체형태로 만들어주어 id와 text값을 가진다.
실행화면
수정버튼 생성
수정 클릭시 input rendering
수정 완료