import * as dayjs from "dayjs";
import { Dayjs } from "dayjs";
import { useEffect, useState } from "react";
export const getMonth = (month = dayjs().month()) => {
const year = dayjs().year();
const firstDayOfMonth = dayjs(new Date(year, month, 1)).day();
let currentMonthCount = 0 - firstDayOfMonth;
return new Array(5).fill([]).map(() => {
return new Array(7).fill(null).map(() => {
currentMonthCount++;
return dayjs(new Date(year, month, currentMonthCount));
});
});
};
const HeadlessDatePicker = () => {
const [currentMonth, setCurrentMonth] = useState<Array<Dayjs[]>>(
getMonth(),
);
const [monthIndex, setMonthIndex] = useState(dayjs().month());
useEffect(() => {
setCurrentMonth(getMonth(monthIndex));
}, [monthIndex]);
const handlePrevMonth = () => {
return setMonthIndex(monthIndex - 1);
};
const handleNextMonth = () => {
return setMonthIndex(monthIndex + 1);
};
const isCurrentDay = (day: Dayjs) => {
return (
dayjs(new Date()).format("DD-MM, YYYY") ===
day.format("DD-MM, YYYY")
);
};
const handleClick = (day: Dayjs) => {
console.log(day)
};
return (
<div>
<div className={"flex gap-20"}>
<div className={"w-32 text-center font-semibold "}>
{dayjs(new Date(dayjs().year(), monthIndex)).format(
"MMMM, YYYY",
)}
</div>
<div className={"flex space-x-3"}>
<button onClick={handlePrevMonth}>prev</button>
<button onClick={handleNextMonth}>next</button>
</div>
</div>
<div
className={` grid uppercase content-center text-xs h-12 grid-cols-7 text-center `}
>
<div>Sun</div>
<div>Mon</div>
<div>Tue</div>
<div>Wed</div>
<div>Thu</div>
<div>Fri</div>
<div>Sat</div>
</div>
<div
className={`grid grid-cols-7 border-t-[1px] border-l-[1px] border-accent1 calender-day-wrapper`}
>
{currentMonth.map((row) => {
return row.map((day) => (
<div
onClick={() => handleClick(day)}
className={`${isCurrentDay(day) && "bg-red-500 "}`}
>
{day.format("DD")}
</div>
));
})}
</div>
</div>
);
};
export default HeadlessDatePicker;
Last active
January 11, 2024 19:31
-
-
Save Bonny-kato/753745c3709a3bab7972c4bc58195a99 to your computer and use it in GitHub Desktop.
The code snippet defines a HeadlessDatePicker component that displays a calendar. It uses the dayjs library to get the current month and year, and generates an array representing the days of the month. The component allows the user to navigate to the previous or
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment