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. <div className="input-group-prepend">
  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. 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="btn-group mr-2">
  55. <DatePicker
  56. selectsRange
  57. startDate={startDate}
  58. endDate={endDate}
  59. onChange={changeHandler}
  60. customInput={<CustomInput />}
  61. />
  62. </div>
  63. );
  64. };