DateRangePicker.tsx 1.9 KB

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