-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patheditableTodo.js
More file actions
45 lines (40 loc) · 1 KB
/
Copy patheditableTodo.js
File metadata and controls
45 lines (40 loc) · 1 KB
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
import { useState } from "react";
export default function EditableTodo() {
const [todos, setTodos] = useState([
{ id: 1, title: "Learn React", editing: false },
{ id: 2, title: "Practice JS", editing: false },
]);
const updateTodo = (id, value) => {
setTodos((prev) =>
prev.map((todo) =>
todo.id === id ? { ...todo, title: value } : todo
)
);
};
const toggleEdit = (id) => {
setTodos((prev) =>
prev.map((todo) =>
todo.id === id ? { ...todo, editing: !todo.editing } : todo
)
);
};
return (
<ul>
{todos.map((todo) => (
<li key={todo.id}>
{todo.editing ? (
<input
value={todo.title}
onChange={(e) => updateTodo(todo.id, e.target.value)}
/>
) : (
<span>{todo.title}</span>
)}
<button onClick={() => toggleEdit(todo.id)}>
{todo.editing ? "Save" : "Edit"}
</button>
</li>
))}
</ul>
);
}