forked from tastejs/todomvc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTodoItem.js
59 lines (52 loc) · 1.62 KB
/
TodoItem.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
import React, { useCallback, useRef, useState } from "react";
import useOnClickOutside from "use-onclickoutside";
import useDoubleClick from "../hooks/useDoubleClick";
import useOnEnter from "../hooks/useOnEnter";
import useTodos from "../reducers/useTodos";
export default function TodoItem({ todo }) {
const [, { deleteTodo, setLabel, toggleDone }] = useTodos(() => null);
const [editing, setEditing] = useState(false);
const onDelete = useCallback(() => deleteTodo(todo.id), [todo.id]);
const onDone = useCallback(() => toggleDone(todo.id), [todo.id]);
const onChange = useCallback(event => setLabel(todo.id, event.target.value), [
todo.id
]);
const handleViewClick = useDoubleClick(null, () => setEditing(true));
const finishedCallback = useCallback(
() => {
setEditing(false);
setLabel(todo.id, todo.label.trim());
},
[todo]
);
const onEnter = useOnEnter(finishedCallback, [todo]);
const ref = useRef();
useOnClickOutside(ref, finishedCallback);
return (
<li
onClick={handleViewClick}
className={`${editing ? "editing" : ""} ${todo.done ? "completed" : ""}`}
>
<div className="view">
<input
type="checkbox"
className="toggle"
checked={todo.done}
onChange={onDone}
autoFocus={true}
/>
<label>{todo.label}</label>
<button className="destroy" onClick={onDelete} />
</div>
{editing && (
<input
ref={ref}
className="edit"
value={todo.label}
onChange={onChange}
onKeyPress={onEnter}
/>
)}
</li>
);
}