1 | import React, { MouseEventHandler } from "react";
|
2 |
|
3 | import { isSameDay } from "date-fns";
|
4 | import {
|
5 | DateRange,
|
6 | DayButtonProps,
|
7 | DayPicker,
|
8 | useDayPicker
|
9 | } from "react-day-picker";
|
10 |
|
11 | function DayWithShiftKey(props: DayButtonProps) {
|
12 | const { selected } = useDayPicker({ mode: "range" });
|
13 |
|
14 | const handleClick: MouseEventHandler<HTMLButtonElement> = (e) => {
|
15 | const requireShiftKey =
|
16 | selected?.from && !isSameDay(props.day.date, selected.from);
|
17 |
|
18 | if (!e.shiftKey && requireShiftKey) {
|
19 | return;
|
20 | }
|
21 | props.onClick?.(e);
|
22 | };
|
23 | return (
|
24 | <button {...props} onClick={handleClick}>
|
25 | {props.children}
|
26 | </button>
|
27 | );
|
28 | }
|
29 |
|
30 | export function RangeShiftKey() {
|
31 | const [range, setRange] = React.useState<DateRange | undefined>({
|
32 | from: undefined
|
33 | });
|
34 |
|
35 | let footer = "Please pick a day.";
|
36 |
|
37 | if (range?.from && !range?.to) {
|
38 | footer = "Press Shift to choose more days.";
|
39 | } else if (range?.to) {
|
40 | const formattedFrom = range.from?.toDateString();
|
41 | const formattedTo = range.to.toDateString();
|
42 | footer = `You selected the days between ${formattedFrom} and ${formattedTo}`;
|
43 | }
|
44 | return (
|
45 | <DayPicker
|
46 | components={{
|
47 | DayButton: DayWithShiftKey
|
48 | }}
|
49 | mode="range"
|
50 | selected={range}
|
51 | onSelect={setRange}
|
52 | footer={footer}
|
53 | />
|
54 | );
|
55 | }
|