Daisy UI Modal
Learn about Daisy UI Modal
What is DaisyUI?
DaisyUI is a component library built on top of Tailwind CSS. It provides ready-made, beautiful UI components like buttons, cards, modals, drawers, and navbars using simple CSS class names. Unlike JavaScript-based component libraries, DaisyUI components are pure CSS and work perfectly with server-rendered HTML and HTMX.
Creating a Modal Component
Instead of navigating to a separate page for the contact form, we will display it inside a modal dialog. DaisyUI provides a "modal" component that uses the HTML dialog element. Create a dialog element in your template with the class "modal". Inside it, place a "modal-box" div that contains the form content.
Triggering the Modal with HTMX
Add a "New Contact" button to the contact list page. Instead of a regular link, give it HTMX attributes: hx-get pointing to a URL that returns the form HTML, and hx-target pointing to a container div where the modal markup will be injected. When the server returns the modal HTML, HTMX inserts it into the page and the modal becomes visible.
Structuring the Modal Template
Create a partial template for the modal. It should contain the dialog element with the modal-open class (to make it visible immediately when injected), a modal-box with a heading, the Django form fields, a submit button, and a close button. The close button should remove the modal from the DOM or close the dialog.
Closing the Modal
After a successful form submission, the server should return a response that removes the modal and refreshes the contact list. You can achieve this by returning an HTMX response that swaps the modal container with empty content and triggers a refresh of the contact list using hx-trigger response headers.
Styling the Modal
Use DaisyUI's modal-backdrop class to add a semi-transparent overlay behind the modal. Apply padding and spacing inside the modal-box for a clean, readable layout. The form inputs should use DaisyUI's form-control, label, and input classes for consistent styling.