dateRangePicker.tsx 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import {useCallback, useMemo} from 'react';
  2. import {DateRange, DateRangeProps, Range, RangeKeyDict} from 'react-date-range';
  3. import CalendarStylesWrapper from './calendarStylesWrapper';
  4. export type DateRangePickerProps = Omit<DateRangeProps, 'ranges' | 'onChange'> & {
  5. onChange: (range: Range) => void;
  6. endDate?: Date;
  7. startDate?: Date;
  8. };
  9. type RangeSelection = {primary: Range};
  10. const PRIMARY_RANGE_KEY = 'primary';
  11. function isRangeSelection(rangesByKey: RangeKeyDict): rangesByKey is RangeSelection {
  12. return rangesByKey?.[PRIMARY_RANGE_KEY] !== undefined;
  13. }
  14. const DateRangePicker = ({
  15. onChange: incomingOnChange,
  16. startDate,
  17. endDate,
  18. ...props
  19. }: DateRangePickerProps) => {
  20. const onChange = useCallback(
  21. (rangesByKey: RangeKeyDict) => {
  22. if (!isRangeSelection(rangesByKey)) {
  23. return;
  24. }
  25. incomingOnChange?.(rangesByKey[PRIMARY_RANGE_KEY]);
  26. },
  27. [incomingOnChange]
  28. );
  29. const ranges: Range[] = useMemo(() => {
  30. return [{startDate, endDate, key: PRIMARY_RANGE_KEY}];
  31. }, [endDate, startDate]);
  32. return (
  33. <CalendarStylesWrapper>
  34. <DateRange {...props} onChange={onChange} ranges={ranges} />
  35. </CalendarStylesWrapper>
  36. );
  37. };
  38. export default DateRangePicker;