-
Notifications
You must be signed in to change notification settings - Fork 0
/
todo.jsx
73 lines (70 loc) · 1.73 KB
/
todo.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
import './styles.css';
import { useRef, useState } from 'react';
const newId = (() => {
let id = 0;
return () => id++;
})();
const INITIAL_TASKS = [
{ id: newId(), task: 'Walk the dog' },
{ id: newId(), task: 'Water the plants' },
{ id: newId(), task: 'Wash the dishes' },
];
export default function App() {
let inputRef = useRef();
const [list, setList] = useState(INITIAL_TASKS);
function addToList() {
if (list.includes(inputRef.current.value)) return;
setList([...list, inputRef.current.value]);
inputRef.current.value = '';
}
return (
<div>
<h1>Todo List</h1>
<form
onSubmit={(e) => {
e.preventDefault();
if (inputRef.current.value.trim() === '') return;
setList([
...list,
{
id: newId(),
task: inputRef.current.value.trim(),
},
]);
}}
>
<input
aria-label={'add new tasks'}
type='text'
ref={inputRef}
placeholder='Add your task'
/>
<div>
<button onClick={addToList}>Submit</button>
</div>
</form>
{list.length === 0 ? (
<div> No Tasks added </div>
) : (
<ul>
{list.map((ele) => (
<li key={ele.id}>
<span>{ele.task}</span>
<button
onClick={() => {
if (window.confirm('Are you sure?')) {
setList((prevList) =>
prevList.filter((l) => l.id != ele.id)
);
}
}}
>
delete
</button>
</li>
))}
</ul>
)}
</div>
);
}