일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- async/await
- map
- SSR
- 인터섹션
- 무한 스크롤
- app router
- Cypress
- 타입 좁히기
- 태그된 유니온
- autosize
- 이분 검색
- 리터럴 타입
- Promise
- 투포인터
- React
- ESlint
- 반공변성
- TS
- 호이스팅
- RTK Query
- recoil
- tailwind
- 결정 알고리즘
- CI/CD
- 공변성
- dfs
- CORS
- useAppDispatch
- webpack
- Jest
Archives
- Today
- Total
짧은코딩
데이터 삭제하기 본문
반응형
-App.js
import { useRef, useState } from "react";
import "./App.css";
import DiaryEditor from "./DiaryEditor";
import DiaryList from "./DiaryList";
const App = () => {
const [data, setData] = useState([]);
const dataId = useRef(0);
const onCreate = (author, content, emotion) => {
const created_date = new Date().getTime();
const newItem = {
author,
content,
emotion,
created_date,
id: dataId.current,
};
dataId.current += 1;
setData([newItem, ...data]);
};
const onDelete = (targetId) => {
console.log(`${targetId}가 삭제되었습니다.`);
const newDiaryList = data.filter((it) => it.id !== targetId);
setData(newDiaryList);
};
return (
<div className="App">
<DiaryEditor onCreate={onCreate} />
<DiaryList onDelete={onDelete} diaryList={data} />
</div>
);
};
export default App;
onDelete를 추가한다. 그리고 DiaryList에 onDelete를 전해준다.
onDelete의 내용은 filter을 이용해서 삭제를 해준다. 그리고 setData를 업데이트 해준다.
-DiaryList.js
import DiaryItem from "./DiaryItem";
const DiaryList = ({ onDelete, diaryList }) => {
return (
<div className="DiaryList">
<h2>일기 리스트</h2>
<h4>{diaryList.length}개의 일기가 있습니다.</h4>
<div>
{diaryList.map((it) => (
<DiaryItem key={it.id} {...it} onDelete={onDelete} />
))}
</div>
</div>
);
};
DiaryList.defaultProps = {
diaryList: [],
};
export default DiaryList;
DiaryItem에 onDelete를 전해준다.
-DiaryItem.js
const DiaryItem = ({
onDelete,
author,
content,
created_date,
emotion,
id,
}) => {
return (
<div className="DiaryItem">
<div className="info">
<span className="anuthor_info">
작성자 : {author} | 감정점수 : {emotion}
</span>
<br />
<span className="date">{new Date(created_date).toLocaleString()}</span>
</div>
<div className="content">{content}</div>
<button
onClick={() => {
if (window.confirm(`${id}번째 일기를 정말 삭제하시겠습니까?`)) {
onDelete(id);
}
}}
>
삭제하기
</button>
</div>
);
};
export default DiaryItem;
삭제하기 버튼을 만든다. 그리고 onDelete에 삭제할 id를 전달하여 삭제한다.
반응형
'인프런, 유데미 > 한입 크기로 잘라 먹는 리액트' 카테고리의 다른 글
Lifecycle 제어하기 (0) | 2022.05.26 |
---|---|
데이터 수정하기 (0) | 2022.05.25 |
데이터 추가하기 (0) | 2022.05.24 |
리스트 렌더링 (0) | 2022.05.24 |
간단한 일기장 프로젝트-State로 사용자 입력처리, useRef (2) | 2022.05.23 |
Comments