✔️ 해당 글은 John Ahn님의 인프런강좌 "따라하며 배우는 리액트 A-Z"를 들으며 작성합니다.
이제 완료 전후를 구분하기 위한 체크박스가 체크되었을 때 아이템 타이틀에 중앙선을 그어주는 효과를 넣겠습니다.
input type="checkbox"를 나타내는 styled component Checkbox에 onChange 함수를 넣습니다.
함수 이름은 handleCompetedChange 이고, map()을 통해 얻은 각 하나의 할 일 아이템의 id를 받습니다
onChange={() => handleCompetedChange(item.id)}
handleCompetedChange 함수를 작성합니다.
const handleCompetedChange = (id) => {
let newTodoData = todoData.map((item) => {
if (item.id === id) {
item.completed = !item.completed;
}
return item;
});
setTodoData(newTodoData);
};
handleCompetedChange 함수는 id를 받아옵니다.
클릭해서 체크박스가 바뀌면(change) 다시 todoData를 map() 돌립니다.
이 때 클릭한 item의 id가 handleCompetedChange 가 받는 id와 동일하면
item.complete(defaultChecked는 false)의 상태가 원래 상태의 역이 됩니다.
item으로 다시 받고, setTodoData를 통해 바뀐 State(newTodoData)로 업데이트해줍니다.
앞서 Item 컴포넌트를 만들 때 이 효과를 위해 getStyle()함수를 만들었습니다.
이제 getStyled()를 completed를 받는 삼항연산자 함수로 수정해 스타일을 동적으로 바꾸겠습니다.
const getStyled = (completed) => {
return {
textDecoration: completed ? "line-through" : "none",
color: completed ? "#89acbe" : "#0c1214",
};
};
completed는 할 일 아이템 Object의 값 중 하나입니다. 기본은 false입니다.
위의 handleCompetedChange를 통해 체크박스를 클릭할 때 마다 각 할 일 아이템 Object(todoData를 map돌렸을 때 찾아내는 Item)의 completed를false 혹은 true로 바꿀 수 있게 만들었습니다.
그 completed의 상태가 true이면 line-through로, false면 none으로 바꿉니다.
기왕 하는 거 글자 색깔도 바꿔줍니다. true일때의 값은 styledComponent in emotion에도 적용시킵니다.
✔️ 참, 이제 임의로 지정한 todoData는 필요없으니 빈 배열로 바꿔둡니다.
// List.jsx에서
const [todoData, setTodoData] = useState([]);
빈 배열이 되니 할 일 아이템 생성 부분의 경계가 흐릿하여 라인을 추가해줍니다.
Todo List 만들기로 배우는 React(feat.Styled component in emotion) - 6 (0) | 2022.09.07 |
---|---|
Todo List 만들기로 배우는 React(feat.Styled component in emotion) - 5 (0) | 2022.09.07 |
Todo List 만들기로 배우는 React(feat.Styled component in emotion) - 3 (0) | 2022.09.06 |
Todo List 만들기로 배우는 React(feat.Styled component in emotion) - 2 (0) | 2022.09.06 |
Todo List 만들기로 배우는 React(feat.Styled component in emotion) - 1 (0) | 2022.09.05 |