UNPKG

2.28 kBTypeScriptView Raw
1import React, { ChangeEventHandler, useState } from "react";
2
3import { format, isAfter, isBefore, isValid, parse } from "date-fns";
4import {
5 DateRange,
6 DayPicker,
7 SelectRangeEventHandler
8} from "react-day-picker";
9
10export function InputRange() {
11 const [selectedRange, setSelectedRange] = useState<DateRange>();
12 const [fromValue, setFromValue] = useState<string>("");
13 const [toValue, setToValue] = useState<string>("");
14
15 const handleFromChange: ChangeEventHandler<HTMLInputElement> = (e) => {
16 setFromValue(e.target.value);
17 const date = parse(e.target.value, "y-MM-dd", new Date());
18 if (!isValid(date)) {
19 return setSelectedRange({ from: undefined, to: undefined });
20 }
21 if (selectedRange?.to && isAfter(date, selectedRange.to)) {
22 setSelectedRange({ from: selectedRange.to, to: date });
23 } else {
24 setSelectedRange({ from: date, to: selectedRange?.to });
25 }
26 };
27
28 const handleToChange: ChangeEventHandler<HTMLInputElement> = (e) => {
29 setToValue(e.target.value);
30 const date = parse(e.target.value, "y-MM-dd", new Date());
31
32 if (!isValid(date)) {
33 return setSelectedRange({ from: selectedRange?.from, to: undefined });
34 }
35 if (selectedRange?.from && isBefore(date, selectedRange.from)) {
36 setSelectedRange({ from: date, to: selectedRange.from });
37 } else {
38 setSelectedRange({ from: selectedRange?.from, to: date });
39 }
40 };
41
42 const handleRangeSelect: SelectRangeEventHandler = (
43 range: DateRange | undefined
44 ) => {
45 setSelectedRange(range);
46 if (range?.from) {
47 setFromValue(format(range.from, "y-MM-dd"));
48 } else {
49 setFromValue("");
50 }
51 if (range?.to) {
52 setToValue(format(range.to, "y-MM-dd"));
53 } else {
54 setToValue("");
55 }
56 };
57
58 return (
59 <div>
60 <DayPicker
61 mode="range"
62 selected={selectedRange}
63 onSelect={handleRangeSelect}
64 />
65 <form className="ma2">
66 <input
67 size={10}
68 placeholder="From Date"
69 value={fromValue}
70 onChange={handleFromChange}
71 />
72 {" – "}
73 <input
74 size={10}
75 placeholder="To Date"
76 value={toValue}
77 onChange={handleToChange}
78 />
79 </form>
80 </div>
81 );
82}