cat phoenix-calendar-component.md

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.

This post used to include a live demo of the component, running in LiveView on this site. The site is static now, so the demo is gone. The code is all on GitHub: leejarvis/phoenix-calendar-component.ex.

The component will send the following 2 events when an action takes place:

  • {:date_selected, %Date{}} - when a date is selected
  • {:month_changed, %Date{}} - when the month is changed

You can then respond in your parent LiveView by handling these events in the handle_info function. For example, when the month changes, you might want to fetch new data from the server and update the calendar accordingly:

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]]}
/>

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.

cd ../writing