저장을 습관화
React - 입문 기록 9 본문
React CRUD 중 DELETE를 구현해보자
Update 때와 같이 게시글 상세보기를 눌렀을때만 Delete 버튼을 나오게 하고 싶으니
기존에 만들어뒀던 contextControl을 활용한다.
Update 텍스트와 Delete 버튼을 빈 태그(<> </>)로 묶어 준 이유는
contextControl이 들어갈 자리가 이미 ul 태그로 묶여있기 때문이다.
Delete 버튼의 onClick 함수를 완성시켜준다.
<li>
<input
type="button"
value="Delete"
onClick={() => {
const newTopics = [];
for (let i = 0; i < topics.length; i++) {
if (topics[i].id !== id) {
newTopics.push(topics[i]);
}
}
setTopics(newTopics);
setMode("WELCOME");
}}
/>
</li>
버튼은 웹 페이지 새로고침을 하지 않기 때문에 event.prevertDefault()는 필요 없다.
흐름은 다음과 같다
const newTopics = [];
빈 배열 newTopics를 선언한다.
for (let i = 0; i < topics.length; i++) {
if (topics[i].id !== id) {
newTopics.push(topics[i]);
}
}
현재 id와 일치하지 않는 요소만 새로운 배열 newTopics에 넣는다.
setTopics(newTopics);
setMode("WELCOME");
새로 만든 배열 newTopics를 topics로 지정하고,
메인 페이지인 WELCOME 모드로 들어간다.
확인
상세보기 상태에서 Delete 버튼 클릭
'JavaScript' 항목이 삭제되고, 메인페이지로 돌아간 것을 확인
DELETE 기능도 완성..
'공부 > React' 카테고리의 다른 글
에러 기록 - Cannot read properties of null (reading 'map') TypeError: Cannot read properties of null (reading 'map') (0) | 2023.10.27 |
---|---|
에러 기록 - React에서는 쓰는 문법은 JavaScript가 아닌 JSX이다. (0) | 2023.10.27 |
React - 입문 기록 8 (0) | 2023.10.25 |
React - 입문 기록 7 (0) | 2023.10.24 |
React - 입문 기록 6 (0) | 2023.10.24 |