DateRangePicker.tsx 2.0 KB

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