84 lines
2.0 KiB
TypeScript
84 lines
2.0 KiB
TypeScript
import { useState } from "react";
|
|
import { Box, Typography, Paper, Popover } from "@mui/material";
|
|
import { DateRange, Range, DateRangeProps } from "react-date-range";
|
|
import { format } from "date-fns";
|
|
|
|
import "react-date-range/dist/styles.css";
|
|
import "react-date-range/dist/theme/default.css";
|
|
|
|
export const DateRangePicker = () => {
|
|
const [range, setRange] = useState<Range[]>([
|
|
{
|
|
startDate: new Date(),
|
|
endDate: new Date(),
|
|
key: "selection"
|
|
}
|
|
]);
|
|
|
|
const [anchorEl, setAnchorEl] = useState<HTMLElement | null>(null);
|
|
|
|
const handleSelect: DateRangeProps['onChange'] = (ranges) => {
|
|
if (ranges.selection) {
|
|
setRange([ranges.selection]);
|
|
if (ranges.selection.endDate !== ranges.selection.startDate) {
|
|
setAnchorEl(null);
|
|
}
|
|
}
|
|
};
|
|
|
|
const handleClick = (event: React.MouseEvent<HTMLElement>) => {
|
|
setAnchorEl(event.currentTarget);
|
|
};
|
|
|
|
const handleClose = () => {
|
|
setAnchorEl(null);
|
|
};
|
|
|
|
const open = Boolean(anchorEl);
|
|
const id = open ? 'date-range-popover' : undefined;
|
|
|
|
return (
|
|
<Box>
|
|
<Popover
|
|
id={id}
|
|
open={open}
|
|
anchorEl={anchorEl}
|
|
onClose={handleClose}
|
|
anchorOrigin={{
|
|
vertical: 'bottom',
|
|
horizontal: 'left',
|
|
}}
|
|
transformOrigin={{
|
|
vertical: 'top',
|
|
horizontal: 'left',
|
|
}}
|
|
>
|
|
<Paper>
|
|
<DateRange
|
|
editableDateInputs={true}
|
|
onChange={handleSelect}
|
|
moveRangeOnFirstSelection={false}
|
|
ranges={range}
|
|
/>
|
|
</Paper>
|
|
</Popover>
|
|
|
|
<Box>
|
|
<Typography
|
|
onClick={handleClick}
|
|
sx={{
|
|
fontSize: '0.875rem',
|
|
cursor: 'pointer',
|
|
p: 1,
|
|
borderRadius: 1,
|
|
'&:hover': {
|
|
backgroundColor: 'action.hover',
|
|
}
|
|
}}
|
|
>
|
|
{format(range[0].startDate ?? new Date(), "PPP")} - {format(range[0].endDate ?? new Date(), "PPP")}
|
|
</Typography>
|
|
</Box>
|
|
</Box>
|
|
);
|
|
} |