티스토리 뷰

React

[React] 실습 / 데이터 삭제 / filter

에스파니아 2022. 4. 29. 15:28
728x90
반응형

개요



React 에서 버튼 이벤트를 통해 데이터를 삭제해 보자 !!

배열 리스트의 데이터를 동적으로 삭제하여 조회해 보자 !!

배열의 filter 함수를 통한 데이터 삭제 스킬을 배워 보자 !!




App.js



2022.04.29 - [React] - [React] 실습 / 데이터 추가 / state 끌어올리기 에서 데이터를 추가 해보는 방법을 배웠다.

데이터 삭제도 마찬가지로,  데이터 흐름을 이해하고 똑같이 적용해주면 된다.

import { useState, useRef } from "react";
import ReportEditor from "./ReportEditor";
import ReportList from "./ReportList";

const App = () => {
  const [data, setData] = useState([]);
  const dataId = useRef(0);

  const onCreate = (author, content, grade) => {
    const newItem = {
      author,
      content,
      grade,
      id: dataId.current
    };
    dataId.current += 1;
    setData([newItem, ...data]);
  };

  const onDelete = (targetId) => {
    const newReportList = data.filter((it) => it.id !== targetId);	//filter 메소드 사용!!
    setData(newReportList);
  };
  
  return (
    <div className="App">
      <ReportEditor onCreate={onCreate} />
      <ReportList onDelete={onDelete} reportList={data} />
    </div>
  );
};
export default App;

공통 부모 컴포넌트에서 삭제 이벤트(OnDelete)를 만들어 ReportList.js 에 prop 으로 전달해 준다.
기존 data State (ReportLIst) 를 filter 메소드를 통해 초기화 해준다.



ReportList.js / ReportItem.js



import ReportItem from "./ReportItem";

const ReportList = ({ onDelete, reportList }) => {
  return (
    <div>
      <h2>보고 리스트</h2>
      {reportList.length}개의 보고가 있습니다.
      <div>
        {reportList.map((it) => {
          return <ReportItem key={it.id} {...it} onDelete={onDelete} />;
        })}
      </div>
    </div>
  );
};

export default ReportList;

App.js -> ReportList.js 로 onDelete 메소드를 전달

const ReportItem = ({ onDelete, id, author, content, grade }) => {
  return (
    <div className="ReportItem">
      <div className="info">
        <span>
          작성자 : {author} | 점수 : {grade}{" "}
        </span>
        <div className="content">{content}</div>
        <button
          onClick={() => {
            console.log(id);
            if (window.confirm(`${id}번째 보고를 정말 삭제할까요?`)) {
              onDelete(id);	//onDelete 메소드 호출 !!!
            }
          }}
        >
          삭제하기
        </button>
      </div>
    </div>
  );
};

export default ReportItem;

ReportList.js -> ReportItem.js 로 onDelete 메소드 전달
ReportItem.js 에서 onDelete 메소드 호출 !!



참고



https://espania.tistory.com/356
 

[React] 실습 / 리스트 조회(rendering)

개요 부모 태그에서 전달받은 데이터를 리스트 형태로 출력 해보자. App.js(부모 태그) import "./App.css"; import ReportList from "./ReportList"; const App = () => { const dummyList = [ { id: 1, author:..

espania.tistory.com

https://espania.tistory.com/361

 

[React] 실습 / 데이터 추가 / state 끌어올리기

개요 React 에서 버튼 이벤트를 통해 데이터를 추가해 보자 !! 배열 리스트의 데이터를 동적으로 추가하여 조회해 보자 !! 컴포넌트 / 구조 React 는 단방향으로만 데이터가 흐르기 때문에 같은 레벨

espania.tistory.com

https://codesandbox.io/s/icy-dew-cyq61t?file=/src/ReportItem.js:0-554 

 

icy-dew-cyq61t - CodeSandbox

icy-dew-cyq61t by jins4731 using react, react-dom, react-scripts

codesandbox.io



728x90
댓글
반응형
250x250
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2026/01   »
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 29 30 31
글 보관함