-
-
Notifications
You must be signed in to change notification settings - Fork 766
Expand file tree
/
Copy pathInput.tsx
More file actions
79 lines (70 loc) · 2.27 KB
/
Input.tsx
File metadata and controls
79 lines (70 loc) · 2.27 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
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
import { format, isValid, parse } from "date-fns";
import React, { useId, useState } from "react";
import { DayPicker } from "react-day-picker";
/** Render an input field bound to a DayPicker calendar. */
export function Input() {
const inputId = useId();
// Hold the month in state to control the calendar when the input changes
const [month, setMonth] = useState(new Date());
// Hold the selected date in state
const [selectedDate, setSelectedDate] = useState<Date | undefined>(undefined);
// Hold the input value in state
const [inputValue, setInputValue] = useState("");
/**
* Function to handle the DayPicker select event: update the input value and
* the selected date, and set the month.
*/
const handleDayPickerSelect = (date: Date | undefined) => {
if (!date) {
setInputValue("");
setSelectedDate(undefined);
} else {
setSelectedDate(date);
setMonth(date);
setInputValue(format(date, "MM/dd/yyyy"));
}
};
/**
* Handle the input change event: parse the input value to a date, update the
* selected date and set the month.
*/
const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setInputValue(e.target.value); // keep the input value in sync
const parsedDate = parse(e.target.value, "MM/dd/yyyy", new Date());
if (isValid(parsedDate)) {
setSelectedDate(parsedDate);
setMonth(parsedDate);
} else {
setSelectedDate(undefined);
}
};
return (
<div>
<label htmlFor={inputId}>
<strong>Date:</strong>
</label>
<input
style={{ fontSize: "inherit", padding: "0.25em 0.5em" }}
id={inputId}
type="text"
value={inputValue}
placeholder="MM/dd/yyyy"
onChange={handleInputChange}
onKeyDown={(e) => {
// Fixes https://github.com/gpbl/react-day-picker/issues/2724 causing search appearing when typing '/'
e.stopPropagation();
}}
/>
<div style={{ marginBlock: "1em" }}>
<DayPicker
month={month}
onMonthChange={setMonth}
mode="single"
selected={selectedDate}
onSelect={handleDayPickerSelect}
footer={`Selected: ${selectedDate?.toDateString()}`}
/>
</div>
</div>
);
}