DateRangePicker.tsx 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import React, {
  2. FC, useRef, forwardRef, useCallback,
  3. } from 'react';
  4. import DatePicker from 'react-datepicker';
  5. import 'react-datepicker/dist/react-datepicker.css';
  6. import { useTranslation } from 'react-i18next';
  7. type CustomInputProps = {
  8. buttonRef: React.Ref<HTMLButtonElement>
  9. onClick?: () => void;
  10. }
  11. const CustomInput = forwardRef<HTMLButtonElement, CustomInputProps>((props: CustomInputProps) => {
  12. const { t } = useTranslation();
  13. return (
  14. <button
  15. type="button"
  16. className="btn btn-outline-secondary dropdown-toggle"
  17. ref={props.buttonRef}
  18. onClick={props.onClick}
  19. >
  20. <i className="fa fa-fw fa-calendar" /> {t('admin:audit_log_management.date')}
  21. </button>
  22. );
  23. });
  24. type DateRangePickerProps = {
  25. startDate: Date | null
  26. endDate: Date | null
  27. onChange: (dateList: Date[] | null[]) => void
  28. }
  29. export const DateRangePicker: FC<DateRangePickerProps> = (props: DateRangePickerProps) => {
  30. const { startDate, endDate, onChange } = props;
  31. const buttonRef = useRef(null);
  32. const changeHandler = useCallback((dateList: Date[] | null[]) => {
  33. if (onChange != null) {
  34. const [start, end] = dateList;
  35. const isSameTime = (start != null && end != null) && (start.getTime() === end.getTime());
  36. if (isSameTime) {
  37. onChange([null, null]);
  38. }
  39. else {
  40. onChange(dateList);
  41. }
  42. }
  43. }, [onChange]);
  44. return (
  45. <div className="btn-group mr-2">
  46. <DatePicker
  47. selectsRange
  48. startDate={startDate}
  49. endDate={endDate}
  50. onChange={changeHandler}
  51. customInput={<CustomInput buttonRef={buttonRef} />}
  52. />
  53. </div>
  54. );
  55. };