-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTodoList.jsx
76 lines (69 loc) · 2.02 KB
/
TodoList.jsx
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
import React, { useState } from 'react';
//import PropTypes from 'prop-types';
import TodoItem from './TodoItem';
function TodoList() {
const [tasks, setTasks] = useState([
{
id: 1,
text: 'Doctor Appointment',
completed: false
},
{
id: 2,
text: 'Meeting at School',
completed: false
}
]);
const [text, setText] = useState(""); // Define text state
const deleteTask = (id) => {
setTasks(tasks.filter(task => task.id !== id));
};
const toggleCompleted = (id) => {
setTasks(tasks.map(task => {
if (task.id === id) {
return { ...task, completed: !task.completed };
} else {
return task;
}
}));
};
const editTask = (id, newText) => {
setTasks(tasks.map(task => {
if (task.id === id) {
return { ...task, text: newText };
} else {
return task;
}
}));
};
const addTask = () => { // Modify addTask to handle adding a task
if (text.trim() !== "") { // Make sure text is not empty
const newTask = {
id: Date.now(),
text,
completed: false
};
setTasks([...tasks, newTask]);
setText(""); // Clear the input after adding task
}
};
return (
<div className="todo-list">
{tasks.map(task => (
<TodoItem
key={task.id}
task={task}
deleteTask={deleteTask}
toggleCompleted={toggleCompleted}
editTask={editTask}
/>
))}
<input
value={text}
onChange={e => setText(e.target.value)}
/>
<button onClick={addTask}>Add</button> {/* Pass addTask directly to onClick */}
</div>
);
}
export default TodoList;