react map

권슬기·2023년 6월 27일
0

react

목록 보기
11/17
const onDelete = (targetId) => {
    console.log(`${targetId}가 삭제되었습니다`);
    const newDiaryList = data.filter((it) => it.id !== targetId);
    setData(newDiaryList);
  };

data.filter로 it을 하나씩 돌리면서 it의 id가 targetId와 일치하지 않으면 필터링 해서 일치하는 애들만 newDiaryList에 담으라는 코드.

리스트에서 제거하고 싶은 애를 제거하고 새 리스트를 짤 때 쓰는 코드.


app 컴포넌트

function App() {
  const [data, setData] = useState([]);

  const onDelete = (targetId) => {
    console.log(`${targetId}가 삭제되었습니다`);
    const newDiaryList = data.filter((it) => it.id !== targetId);
    setData(newDiaryList);
  };

  return (
    <div className="App">
      <DiaryList onDelete={onDelete} diaryList={data} />
    </div>
  );
}

export default App;


자식 컴포넌트 // 제거할 리스트는 DiaryItem에 있음

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>
  );
};

export default DiaryList;

const DiaryItem = ({onDelete, author, content, created_date, emotion, id}) => {
  return (
    <div className="DiaryItem">
      <div className="info">
        <span>
          작성자 : {author} | 감정점수 : {emotion}
        </span>
        <br />
        <span className="date">
          {new Date(created_date).toLocaleDateString()}
        </span>
      </div>
      <div className="content">{content}</div>
      <button
        onClick={() => {
          console.log(id);
          if (window.confirm(`${id}번째를 정말 삭제하시겠습니까?`)) {
            onDelete(id);
          }
        }}>
        삭제
      </button>
    </div>
  );
};

export default DiaryItem;
profile
병아리 프론트엔드 개발자

0개의 댓글

관련 채용 정보