-
Notifications
You must be signed in to change notification settings - Fork 0
/
DateRangePickers.js
80 lines (65 loc) · 2.35 KB
/
DateRangePickers.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
import React, { useState, useEffect, useCallback } from 'react';
import { useHighcharts, useAxis } from 'react-jsx-highstock';
import DayPickerInput from 'react-day-picker/DayPickerInput';
import dateParse from 'date-fns/parse';
import dateFormat from 'date-fns/format';
import startOfDay from 'date-fns/startOfDay'
import 'react-day-picker/lib/style.css';
const DAY_FORMAT = 'dd MMM yyyy';
const ONE_DAY = 86400000;
const parseDate = str => dateParse(str, DAY_FORMAT, new Date());
const formatDate = date => dateFormat(date, DAY_FORMAT);
const DateRangePickers = () => {
const Highcharts = useHighcharts();
const axis = useAxis('xAxis');
const [from, setFrom] = useState(null);
const [to, setTo] = useState(null);
const handleFromDateChange = useCallback(fromDate => {
const newMin = startOfDay(fromDate).valueOf();
const newMax = (newMin >= to) ? newMin + ONE_DAY : to.valueOf();
axis.setExtremes(newMin, newMax);
},[to, axis]);
const handleToDateChange = useCallback(toDate => {
const newMax = startOfDay(toDate).valueOf();
const newMin = (newMax <= from) ? newMax - ONE_DAY : from.valueOf();
axis.setExtremes(newMin, newMax);
},[from, axis]);
useEffect(() => {
if (!axis) return;
const handleAfterSetExtremes = ({ min, max }) => {
setFrom(new Date(min));
setTo(new Date(max));
};
Highcharts.addEvent(axis.object, 'afterSetExtremes', handleAfterSetExtremes);
const { min, max } = axis.getExtremes();
setFrom(new Date(min));
setTo(new Date(max));
return () => {
Highcharts.removeEvent(axis.object, 'afterSetExtremes', handleAfterSetExtremes);
}
}, [axis]);
if (from === null || to === null) {
return null;
}
return (
<div className="date-range-pickers">
<span className="date-range-pickers__from-label">From: </span>
<DayPickerInput
value={from}
format={DAY_FORMAT}
formatDate={formatDate}
parseDate={parseDate}
dayPickerProps={{ month: from }}
onDayChange={handleFromDateChange} />
<span className="date-range-pickers__to-label">To: </span>
<DayPickerInput
value={to}
format={DAY_FORMAT}
formatDate={formatDate}
parseDate={parseDate}
dayPickerProps={{ month: to }}
onDayChange={handleToDateChange} />
</div>
)
};
export default DateRangePickers;