DateRangePicker.tsx 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. import type { FC } from 'react';
  2. import { forwardRef, useCallback } from 'react';
  3. import { addDays } from 'date-fns/addDays';
  4. import { format } from 'date-fns/format';
  5. import DatePicker from 'react-datepicker';
  6. import './DateRangePicker.vendor-styles.prebuilt';
  7. type CustomInputProps = {
  8. value?: string;
  9. onChange?: () => void;
  10. onFocus?: () => void;
  11. };
  12. const CustomInput = forwardRef<HTMLInputElement, CustomInputProps>(
  13. (props: CustomInputProps, ref) => {
  14. const dateFormat = 'MM/dd/yyyy';
  15. const date = new Date();
  16. const placeholder = `${format(date, dateFormat)} - ${format(addDays(date, 1), dateFormat)}`;
  17. return (
  18. <div className="input-group admin-audit-log">
  19. <span className="input-group-text">
  20. <span className="material-symbols-outlined me-1">calendar_month</span>
  21. </span>
  22. <input
  23. ref={ref}
  24. type="text"
  25. value={props?.value}
  26. onFocus={props?.onFocus}
  27. onChange={props?.onChange}
  28. placeholder={placeholder}
  29. className="form-control date-range-picker"
  30. aria-describedby="basic-addon1"
  31. />
  32. </div>
  33. );
  34. },
  35. );
  36. CustomInput.displayName = 'CustomInput';
  37. type DateRangePickerProps = {
  38. startDate: Date | null;
  39. endDate: Date | null;
  40. onChange: (dateList: Date[] | null[]) => void;
  41. };
  42. export const DateRangePicker: FC<DateRangePickerProps> = (
  43. props: DateRangePickerProps,
  44. ) => {
  45. const { startDate, endDate, onChange } = props;
  46. const changeHandler = useCallback(
  47. (dateList: Date[] | null[]) => {
  48. if (onChange != null) {
  49. const [start, end] = dateList;
  50. const isSameTime =
  51. start != null && end != null && start.getTime() === end.getTime();
  52. if (isSameTime) {
  53. onChange([null, null]);
  54. } else {
  55. onChange(dateList);
  56. }
  57. }
  58. },
  59. [onChange],
  60. );
  61. return (
  62. <div className="me-2">
  63. <DatePicker
  64. selectsRange
  65. startDate={startDate}
  66. endDate={endDate}
  67. onChange={changeHandler}
  68. customInput={<CustomInput />}
  69. />
  70. </div>
  71. );
  72. };