DateRangePicker.tsx 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. <span className="input-group-text">
  17. <i className="fa fa-fw fa-calendar" />
  18. </span>
  19. <input
  20. ref={ref}
  21. type="text"
  22. value={props?.value}
  23. onFocus={props?.onFocus}
  24. onChange={props?.onChange}
  25. placeholder={placeholder}
  26. className="form-control date-range-picker"
  27. aria-describedby="basic-addon1"
  28. />
  29. </div>
  30. );
  31. });
  32. CustomInput.displayName = 'CustomInput';
  33. type DateRangePickerProps = {
  34. startDate: Date | null
  35. endDate: Date | null
  36. onChange: (dateList: Date[] | null[]) => void
  37. }
  38. export const DateRangePicker: FC<DateRangePickerProps> = (props: DateRangePickerProps) => {
  39. const { startDate, endDate, onChange } = props;
  40. const changeHandler = useCallback((dateList: Date[] | null[]) => {
  41. if (onChange != null) {
  42. const [start, end] = dateList;
  43. const isSameTime = (start != null && end != null) && (start.getTime() === end.getTime());
  44. if (isSameTime) {
  45. onChange([null, null]);
  46. }
  47. else {
  48. onChange(dateList);
  49. }
  50. }
  51. }, [onChange]);
  52. return (
  53. <div className="me-2">
  54. <DatePicker
  55. selectsRange
  56. startDate={startDate}
  57. endDate={endDate}
  58. onChange={changeHandler}
  59. customInput={<CustomInput />}
  60. />
  61. </div>
  62. );
  63. };