Calendar
Overview
Calendar is a powerful component to manage date. It is gretly inspired by DevDojo. Many things can be done with this component. Let see what we can achieve with examples below. It is used into DatePicker component.
Default Calendar
Basicly, this example shows the minimum requirement to use Calendar. Calendar provides you a set of custom listener you can use to do whatever suit best to your feature.
Here we retrieve selected date with @select-date props custom event.
Copied !
---
import Calendar from "$components/calendar/Calendar.astro";
---
<div
x-data={`
{
date: null,
formattedDate: "",
}
`}
class="bg-white w-full"
>
<div class="border flex gap-x-2 p-4 rounded">
<span class="shrink-0">Date Value:</span>
<span x-text="date"></span>
</div>
<div class="border flex gap-x-2 p-4 rounded">
<span class="shrink-0">Formatted Date:</span>
<span x-text="formattedDate"></span>
</div>
<Calendar
id="default-calendar"
x-ref="datePicker"
x-on:select-date="console.log($event.detail); date = $event.detail.date; formattedDate = $event.detail.formattedDate"
/>
</div>
Multiple Select Calendar
Multiple dates can be selected. However, it’s up to you to define how multiple dates will be selected.
Don’t worry, with @select-date props custom event, it’s an easy trick. See example below.
P.S: Note that you have selectedDayClass props which allow to define cell day class based on its state.
Selected Dates
Copied !
---
import Calendar from "$components/calendar/Calendar.astro";
---
<div
x-data={`
{
dates: [],
isDayEqualsToToday(day) {
return new Date().getDate() === day;
},
isSelectedDayInDates(day, dates) {
return dates.some((item) => item.date.getDate() === day);
}
}
`}
class="bg-white w-full"
>
<div class="border flex flex-col gap-y-2 p-4 rounded">
<h3 class="text-center">Selected Dates</h3>
<ul
class="grid grid-cols-2 xl:grid-cols-4 gap-4 items-center justify-center"
>
<template x-for="date in dates">
<li class="w-full flex justify-center">
<span class="text-sm" x-text="date.formattedDate"></span>
</li>
</template>
</ul>
</div>
<Calendar
id="multiple-select-calendar"
stateDayClass={`{
'bg-primary-200': isDayEqualsToToday(day),
'text-gray-600 hover:bg-primary-200': !(isDayEqualsToToday(day) && isSelectedDayInDates(day, dates)),
'bg-primary-500 text-white hover:bg-opacity-75': isSelectedDayInDates(day, dates)
}`}
x-ref="datePicker"
@select-date="dates = [...dates, $event.detail];"
@reset-date="dates = [];"
showResetAndTodayButtons
/>
</div>