This repository has been archived by the owner on Oct 9, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 30
/
TodoItem.js
81 lines (72 loc) · 1.79 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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import React, { useState, useEffect } from 'react'
import classNames from 'classnames'
const ESCAPE_KEY = 27
const ENTER_KEY = 13
const TodoItem = (props) => {
const [editText, setEditText] = useState(props.todo.title);
const editField = React.useRef(null)
useEffect(() => {
if (!editField.current && props.editing) {
const node = editField.current
node.focus()
node.setSelectionRange(node.value.length, node.value.length)
}
})
const handleSubmit = event => {
const {onDestroy, onSave } = props
var val = editText.trim()
if (val) {
onSave(val)
setEditText(val)
} else {
onDestroy()
}
}
const handleEdit = () => {
const { onEdit, todo } = props
onEdit()
setEditText(todo.title)
}
const handleKeyDown = event => {
const { onCancel, todo } = props
if (event.which === ESCAPE_KEY) {
setEditText(todo.title)
onCancel(event)
} else if (event.which === ENTER_KEY) {
handleSubmit(event)
}
}
const handleChange = event => {
if (props.editing) {
setEditText(event.target.value)
}
}
const { editing, onDestroy, onToggle, todo } = props
return (
<li className={classNames({
completed: todo.completed,
editing: editing,
})}>
<div className="view">
<input
className="toggle"
type="checkbox"
checked={todo.completed}
onChange={onToggle}
/>
<label onDoubleClick={handleEdit}>
{todo.title}
</label>
<button className="destroy" onClick={onDestroy} />
</div>
<input
ref={editField}
className="edit"
value={editText}
onChange={handleChange}
onKeyDown={handleKeyDown}
/>
</li>
)
}
export default TodoItem