-
Notifications
You must be signed in to change notification settings - Fork 0
/
calendar.tsx
75 lines (69 loc) · 2 KB
/
calendar.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import * as React from "react";
import "./styles.css";
import {
getNextMonth,
getPreviousMonth,
getCalendarDaysForMonth,
newDate,
dateEqual,
TDate
} from "./utils";
export default function App() {
const [activeMonth, setActiveMonth] = React.useState<TDate>([2020, 0, 1]);
const [selectedDate, setSelectedDate] = React.useState<TDate>();
const changeMonth = (val: number) => {
const newDate =
val > 0 ? getNextMonth(activeMonth) : getPreviousMonth(activeMonth);
setActiveMonth(newDate);
};
const days = getCalendarDaysForMonth(activeMonth).map((week, i) => {
return (
<div className="week" key={`week-${i}`}>
{week.map((day, j) => {
const selected = dateEqual(day.date, selectedDate);
return (
<div
key={`day-${i}-${j}`}
className={`day ${day.isFromNextMonth && "day-next-month"} ${
day.isFromPreviousMonth && "day-previous-month"
} ${selected && "day-selected"}`}
onClick={() => {
if (selected) {
setSelectedDate(undefined);
} else {
setSelectedDate(day.date);
}
}}
>
{day.date[2]}
</div>
);
})}
</div>
);
});
return (
<div className="App">
<div className="calendar">
<div className="controls">
<div className="controls-button" onClick={() => changeMonth(-1)}>
{"<"}
</div>
<div>
{newDate(activeMonth).toLocaleDateString(undefined, {
year: "numeric",
month: "long"
})}
</div>
<div className="controls-button" onClick={() => changeMonth(1)}>
{">"}
</div>
</div>
<div className="days">{days}</div>
</div>
<div className="selected-date">
{selectedDate && newDate(selectedDate).toLocaleDateString()}
</div>
</div>
);
}