Phoenix LiveView Calendar Component
I recently had reason to build a calendar component in Phoenix LiveView. It was a small but fun part of a larger project I'm working on, and something I wanted to share in case anyone else out there is interested in a drop-in calendar component for their LiveView project.
Let's skip the preamble and and just show the stuff. Here's what the calendar looks like:
December
The component will send the following 2 events when an action takes place:
{:date_selected, %Date{}}
- when a date is selected (current: 2024-12-12){:month_changed, %Date{}}
- when the month is changed (current: December)
You can then respond in your parent LiveView by handling these events in the
def handle_info({:month_changed, date}, socket) do
{:noreply, assign(socket, data: fetch_data(date))}
end
You can also pass in a list of dates to the component, which will be highlighted on the calendar:
<.live_component id="calendar"
module={CalendarComponent}
highlighted_dates={[~D[2024-08-01], ~D[2024-10-07], ~D[2024-10-11]]}
/>
The code for the component can be found on GitHub: leejarvis/phoenix-calendar-component.ex . Feel free to ridicule it in the issue tracker.
No libraries and no setup. Just drop it into your LiveView.
That's it. That's the whole post.