-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathApp.js
93 lines (86 loc) · 2.36 KB
/
App.js
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
import { useState, useRef, useCallback } from 'react';
import ToDoEdit from './components/ToDoEdit';
import ToDoInsert from './components/ToDoInsert';
import TodoList from './components/TodoList';
import TodoTemplate from './components/ToDoTemplate';
function App() {
const [todos, setTodos] = useState([
{
id: 1,
text: '리액트 기초 알아보기',
checked: true,
},
{
id: 2,
text: '컴포넌트 스타일링 하기',
checked: true,
},
{
id: 3,
text: '투두리스트 만들기',
checked: false,
},
]);
const [selectedTodo, setSelectedTodo] = useState(null);
const [insertToggle, setInsertToggle] = useState(false);
const nextId = useRef(4);
const onInsertToggle = useCallback(() => {
if (selectedTodo) {
setSelectedTodo((selectedTodo) => null);
}
setInsertToggle((prev) => !prev);
}, [selectedTodo]);
const onChangeSelectedTodo = (todo) => {
setSelectedTodo((selectedTodo) => todo);
};
const onInsert = useCallback((text) => {
const todo = {
id: nextId.current,
text,
checked: false,
};
setTodos((todos) => todos.concat(todo)); //concat(): 인자로 주어진 배열이나 값들을 기존 배열에 합쳐서 새 배열 반환
nextId.current++; //nextId 1씩 더하기
}, []);
const onRemove = useCallback((id) => {
setTodos((todos) => todos.filter((todo) => todo.id !== id));
}, []);
const onUpdate = useCallback(
(id, text) => {
onInsertToggle();
setTodos((todos) =>
todos.map((todo) => (todo.id === id ? { ...todo, text } : todo)),
);
},
[onInsertToggle],
);
const onToggle = useCallback((id) => {
setTodos((todos) =>
todos.map((todo) =>
todo.id === id ? { ...todo, checked: !todo.checked } : todo,
),
);
}, []);
return (
<TodoTemplate>
<ToDoInsert onInsert={onInsert} />
<TodoList
todos={todos}
onToggle={onToggle}
onRemove={onRemove}
onChangeSelectedTodo={onChangeSelectedTodo}
onInsertToggle={onInsertToggle}
/>
{insertToggle && (
<ToDoEdit
onInsert={onInsert}
selectedTodo={selectedTodo}
onInsertToggle={onInsertToggle}
onUpdate={onUpdate}
insertToggle={insertToggle}
/>
)}
</TodoTemplate>
);
}
export default App;