React 상위 컴포넌트에서 상태를 선언한 경우 꼭 setState나 useRecoilState 등도 함께 받아와주자.
// 상위 컴포넌트
// Todolist.component
export default function TodoList({ onDelete, onChangeDone, onUpdateTodoText }) {
const todos = useRecoilValue(todoListState);
const doneItems = useRecoilValue(doneListState);
return (
<StyledTodoList>
<h2>To Do List</h2>
<ul>
{todos.map(todo => {
return (
<TodoItem
key={todo.id}
todo={todo}
isDone={todo.done}
onChangeDone={onChangeDone}TodoItem
onDelete={onDelete}
onUpdateTodoText={onUpdateTodoText}
/>
);
})}
</ul>
<h2>Done List</h2>
<ul>
{doneItems.map(doneItem => {
return <li key={doneItem.id}>{doneItem.text}</li>;
})}
</ul>
</StyledTodoList>
);
}
const StyledTodoList = styled.div`
flex-grow: 3;
height: 300px;
width: 300px;
\`;
// 하위 컴포넌트
// TodoItem.component
export default function TodoItem({ todo, isDone, onDelete, onChangeDone, onUpdateTodoText }) {
const [isEditClicked, setIsEditClicked] = useState(false);
const [updateTextItem, setUpdateTextItem] = useState(todo.todo);
const onChangeUpdateTextItem = e => {
setUpdateTextItem(e.target.value);
};
const onKeyDown = e => {
if (e.key === "Enter") {
onUpdateTodoText(todo.id, updateTextItem);
setIsEditClicked(false);
}
};
const handleClickButton = () => {
if (isEditClicked) {
onUpdateTodoText(todo.id, updateTextItem);
setIsEditClicked(false);
} else {
setIsEditClicked(true);
}
};
return (
<li>
{isEditClicked ? (
<Input
value={updateTextItem}
onChange={onChangeUpdateTextItem}
onKeyDown={onKeyDown} />
) : (
<Checkbox
isChecked={todo.done}
onChangeChecked={() => {
onChangeDone(todo.id);
}}
\>
{todo.todo}
</Checkbox>
)}
{isDone ? "" : <Button onClick={handleClickButton}>{isEditClicked ? "✔️" : "✏️"}</Button>}
<Button onClick={() => onDelete(todo.id)}>X</Button>
</li>
);
}