forked from ReactTraining/hooks-workshop
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMinutes.js
83 lines (76 loc) · 1.87 KB
/
Minutes.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
82
83
import React, { useState } from "react"
import { format as formatDate } from "date-fns"
import { FaMinus, FaPlus } from "react-icons/fa"
export default function Minutes({ date }) {
const [minutes, setMinutes] = useState(30)
const subtract = () => {
if (minutes > 0) {
setMinutes(minutes - 1)
}
}
const add = () => {
setMinutes(minutes + 1)
}
const handleInputChange = event => {
const value = event.target.value
const specialCaseEmpty = value.trim() === ""
if (specialCaseEmpty) {
// allow them to delete all characters
setMinutes(value)
} else {
const int = parseInt(event.target.value, 10)
// disallow non-numeric values
if (!isNaN(int)) {
setMinutes(int)
}
}
}
const handleInputBlur = event => {
if (event.target.value.trim() === "") {
setMinutes(0)
}
}
const handleInputKeyDown = event => {
// preventDefault to keep cursor from going back/forth
if (event.key === "ArrowUp") {
event.preventDefault()
add()
} else if (event.key === "ArrowDown") {
event.preventDefault()
subtract()
}
}
return (
<div className="Minutes">
<div>
<button
type="button"
className="icon_button Minutes_button"
onClick={subtract}
>
<FaMinus />
</button>
</div>
<input
className="Minutes_input"
value={minutes}
id="minutes"
onChange={handleInputChange}
onBlur={handleInputBlur}
onKeyDown={handleInputKeyDown}
/>
<div>
<button
type="button"
className="icon_button Minutes_button"
onClick={add}
>
<FaPlus />
</button>
</div>
<label className="Minutes_label" htmlFor="minutes">
Mins on {formatDate(date, "MMM Do")}
</label>
</div>
)
}