forked from ReactTraining/hooks-workshop
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDateFields.js
89 lines (81 loc) · 2.38 KB
/
DateFields.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
84
85
86
87
88
89
import React, { createContext, useContext } from "react"
import { daysInMonth } from "app/utils"
const Context = createContext()
export function DateFields({
children,
defaultValue,
start,
end,
value: controlledValue,
onChange
}) {
const date = controlledValue || defaultValue
const context = { date, onChange }
return <Context.Provider value={context} children={children} />
}
export function DayField(props) {
const { date, onChange } = useContext(Context)
const month = date.getMonth()
const year = date.getFullYear()
const days = Array.from({ length: daysInMonth(month, year) })
const value = date.getDate()
const handleChange = event => {
const newDate = new Date(date.getTime())
newDate.setDate(parseInt(event.target.value))
onChange(newDate)
}
return (
<select value={value} onChange={handleChange} {...props}>
{days.map((_, index) => (
<option key={index} value={index + 1}>
{index < 9 ? "0" : ""}
{index + 1}
</option>
))}
</select>
)
}
export function MonthField(props) {
const { date, onChange } = useContext(Context)
const month = date.getMonth()
const handleChange = event => {
const newDate = new Date(date.getTime())
newDate.setMonth(parseInt(event.target.value))
onChange(newDate)
}
return (
<select value={month} onChange={handleChange} {...props}>
<option value="0">01</option>
<option value="1">02</option>
<option value="2">03</option>
<option value="3">04</option>
<option value="4">05</option>
<option value="5">06</option>
<option value="6">07</option>
<option value="7">08</option>
<option value="8">09</option>
<option value="9">10</option>
<option value="10">11</option>
<option value="11">12</option>
</select>
)
}
export function YearField({ start, end, ...rest }) {
const { date, onChange } = useContext(Context)
const difference = end - start + 1
const years = Array.from({ length: difference }).map(
(_, index) => index + start
)
const handleChange = event => {
const newDate = new Date(date.getTime())
newDate.setYear(parseInt(event.target.value), 1)
onChange(newDate)
}
return (
<select value={date.getFullYear()} onChange={handleChange} {...rest}>
{years.map(year => (
<option key={year}>{year}</option>
))}
</select>
)
}