UNPKG

1.14 kBTypeScriptView Raw
1import React, { useState } from "react";
2
3import { endOfWeek, startOfWeek } from "date-fns";
4import { DateRange, DayPicker, rangeIncludesDate } from "react-day-picker";
5
6/** Select the whole week when the day is clicked. */
7export function CustomWeek() {
8 const [selectedWeek, setSelectedWeek] = useState<DateRange | undefined>();
9
10 return (
11 <DayPicker
12 showWeekNumber
13 showOutsideDays
14 modifiers={{
15 selected: selectedWeek,
16 range_start: selectedWeek?.from,
17 range_end: selectedWeek?.to,
18 range_middle: (date: Date) =>
19 selectedWeek ? rangeIncludesDate(selectedWeek, date, true) : false
20 }}
21 onDayClick={(day, modifiers) => {
22 if (modifiers.selected) {
23 setSelectedWeek(undefined); // clear the selection if the week is already selected
24 return;
25 }
26 setSelectedWeek({
27 from: startOfWeek(day),
28 to: endOfWeek(day)
29 });
30 }}
31 footer={
32 selectedWeek &&
33 `Week from ${selectedWeek?.from?.toLocaleDateString()} to
34 ${selectedWeek?.to?.toLocaleDateString()}`
35 }
36 />
37 );
38}