> For the complete documentation index, see [llms.txt](https://simplereact.gitbook.io/simplereact/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://simplereact.gitbook.io/simplereact/09.-todo-app-delete.md).

# 09. TODO APP (DELETE)

Todo APP 을 만들어봅니다

### 들어가기전에&#x20;

이번 내용은 08. TODO APP (Read, Create) 와 이어집니다.\
이전에는 Todo 를 추가하는 방법에 대해 학습했습니다. 이번 챕터에서는 추가된 데이터를 삭제하는 방법에 대해 학습합니다.

### 실습

이전 Input 에서 추가한 text 를 App.js 에게 전달하여 데이터를 추가했던 방법을 기억하시나요 ? \
데이터의 삭제도 비슷한 흐름으로 이루어집니다. \
event 는 Contents 에서 일어나지만 실제 데이터의 변화는 App.js 에서 일어납니다.

#### Delete Function 추가

먼저 App.js 에 데이터를 삭제하는 함수를 추가해보겠습니다.\
삭제를 하는 방법은 여러가지 방법이 존재하지만 우리는 array 의 filter 를 이용해서 삭제를 해보겠습니다.\
함수는 매우 간단합니다. contents 에서 눌린 Todo 의 id 를 넘겨주면 App.js 에서는 넘겨받은 id 와 다른 Todo 들만 필터링해서 데이터를 변경하면 됩니다.

```javascript
// App.js

import React, { useState } from "react";

import Header from "./components/header";
import Contents from "./components/contents";
import Footer from "./components/footer";

function App() {
  const [todos, setTodos] = useState([]);

  const handleAdd = text => {
    setTodos([
      ...todos,
      {
        id: Date.now(),
        text,
        isDone: false
      }
    ]);
  };

  const handleDelete = id => { // Contents 에게 넘겨줄 todo 를 삭제하는 함수
    setTodos(todos.filter(todo => todo.id !== id));
  };

  return (
    <div>
      <Header onChange={handleAdd} />
      <Contents todos={todos} onDelete={handleDelete} />
      <Footer />
    </div>
  );
}

export default App;
```

#### Todo 삭제

Contents 에서는 부모로부터 넘겨받은 onDelete 라는 함수에게 눌린 Todo 의 id 를 넘겨줄거에요&#x20;

```javascript
// src/components/contens.js

import React from "react";

function Todo({ todo: { id, text, isDone }, onDelete }) {
  return (
    <div>
      <input type="checkbox" checked={isDone} />
      <span>{text}</span>
      <button onClick={() => onDelete(id)}>DELETE</button>
    </div>
  );
}

function Contents({ todos, onDelete }) {
  return (
    <div>
      {todos.map(todo => (
        <Todo todo={todo} onDelete={onDelete} key={todo.id} />
      ))}
    </div>
  );
}

export default Contents;
```

App.js 에서 받은 함수를 Contents 로 넘겨주고 Contents 가 Todo 로 다시 한번 넘겨줍니다.\
그리고 Todo 에서는 클릭되었을 때 넘겨받은 함수로 id 를 넘겨줍니다.\
\
이 처럼 부모에 있는 데이터를 다루기 위해서 함수를 넘기다보면 Component 들의 깊이가 깊어질수록 같은 함수를 여러번 넘기게 되는 일이 발생합니다. \
지금은 두 번 정도라 한 눈에 보이지만 조금만 더 복잡해지더라도 흐름을 따라가는게 벅찹니다.\
\
**=> Header, Contents, Footer 에서 같은 Todo List 를 필요로 하기 때문에 이 모든걸 감싸고 있는 App.js 로 함수가 몰리기 때문에 발생하는 일 입니다.**

이를 해결하기 위해서는 Global 하게 State 를 관리 할 수 있는 수단이 필요합니다. 대표적으로 많이 쓰이는것이 Redux, Mobx 같은 라이브러리입니다. 우리는 뒤쪽에서 Context API 를 이용하여 이러한 문제를 풀어보려고합니다.

![](https://707901708-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LmntoQaR_UpEAiZTdQt%2F-LonvybT0DN1bgrYevHc%2F-Loo-a_teWYeSxLnpHGO%2FKapture%202019-09-15%20at%2017.20.07.gif?alt=media\&token=ddddeab7-e97f-4b7f-8fa0-6bcb6e7d26d2)
