import React, { useState, useCallback } from 'react';
import PropTypes from 'prop-types';
import moment from 'moment';
/** REACT DATES */
import { DateRangePicker, isInclusivelyBeforeDay } from 'react-dates';
import 'react-dates/initialize';
import 'react-dates/lib/css/_datepicker.css';
import './DateRange.css';
const today = moment();
const lastWeek = moment().subtract(7, 'day');
const lastMonth = moment().subtract(1, 'month');
const studyDatePresets = [
{
text: 'Today',
start: today,
end: today,
},
{
text: 'Last 7 days',
start: lastWeek,
end: today,
},
{
text: 'Last 30 days',
start: lastMonth,
end: today,
},
];
const renderYearsOptions = () => {
const currentYear = moment().year();
const options = [];
for (let i = 0; i < 20; i++) {
const year = currentYear - i;
options.push(
);
}
return options;
};
const DateRange = props => {
const { id, onChange, startDate, endDate } = props;
const [focusedInput, setFocusedInput] = useState(null);
const renderYearsOptionsCallback = useCallback(renderYearsOptions, []);
const renderDatePresets = () => {
return (
{studyDatePresets.map(({ text, start, end }) => {
return (
);
})}
);
};
const renderMonthElement = ({ month, onMonthSelect, onYearSelect }) => {
renderMonthElement.propTypes = {
month: PropTypes.object,
onMonthSelect: PropTypes.func,
onYearSelect: PropTypes.func,
};
const handleMonthChange = event => {
onMonthSelect(month, event.target.value);
};
const handleYearChange = event => {
onYearSelect(month, event.target.value);
};
const handleOnBlur = () => {};
return (
);
};
// Moment
const parsedStartDate = startDate ? moment(startDate, 'YYYYMMDD') : null;
const parsedEndDate = endDate ? moment(endDate, 'YYYYMMDD') : null;
return (
{
onChange({
startDate: newStartDate ? newStartDate.format('YYYYMMDD') : undefined,
endDate: newEndDate ? newEndDate.format('YYYYMMDD') : undefined,
});
}}
focusedInput={focusedInput}
onFocusChange={updatedVal => setFocusedInput(updatedVal)}
/** OPTIONAL */
renderCalendarInfo={renderDatePresets}
renderMonthElement={renderMonthElement}
startDatePlaceholderText={'Start Date'}
endDatePlaceholderText={'End Date'}
phrases={{
closeDatePicker: 'Close',
clearDates: 'Clear dates',
}}
isOutsideRange={day => !isInclusivelyBeforeDay(day, moment())}
hideKeyboardShortcutsPanel={true}
numberOfMonths={1}
showClearDates={false}
anchorDirection="left"
/>
);
};
DateRange.defaultProps = {
id: '',
startDate: null,
endDate: null,
};
DateRange.propTypes = {
id: PropTypes.string,
/** YYYYMMDD (19921022) */
startDate: PropTypes.string,
/** YYYYMMDD (19921022) */
endDate: PropTypes.object,
/** Callback that received { startDate: string(YYYYMMDD), endDate: string(YYYYMMDD)} */
onChange: PropTypes.func.isRequired,
};
export default DateRange;