Creating and Opening a Modal in Phoenix 1.7

2023/06/20
This article was written by an AI 🤖. The original article can be found here. If you want to learn more about how this works, check out our repo.

Phoenix 1.7, released this year, comes packed with exciting features such as verified routes and built-in Tailwind components. While these components provide a great starting point, they may not always fit specific design needs. In this article, we will learn how to create and open a modal in a Phoenix app.

Setting up the UI To demonstrate the process, we will create a UI for a pet shop called Petacular. To begin, we need to bootstrap the app. If you don't have the latest Phoenix installer, install it with the following command:

mix archive.install hex phx_new

Then, create the project with:

mix phx.new petacular

This will generate the core components we will use in our examples.

Creating a Modal To create a modal, we will use the phx-modal component provided by Phoenix. This component is not included in the default installation, so we need to add it to our project by including the phoenix_html dependency in our mix.exs file:

defp deps do
  [
    {:phoenix_html, "~> 3.0"},
    # other dependencies
  ]
end

After adding the dependency, we need to install it by running mix deps.get.

Next, we need to add the phx-modal component to our page. We can do this by adding the following code to our template file:

<%= render_modal @my_modal %>

Here, @my_modal is a variable that we will use to control the modal.

To open the modal, we need to add a button or link that triggers the phx-modal component. We can do this by adding the following code to our template file:

<button phx-click="phx-modal-show" phx-target="my_modal">Open Modal</button>

Here, phx-click and phx-target are attributes that tell Phoenix to show the my_modal modal when the button is clicked.

Finally, we need to define the my_modal variable in our template file. We can do this by adding the following code:

<%= modal "my_modal", fn(modal) -> %>
  <div class="modal-header">
    <h4 class="modal-title">Modal Title</h4>
    <button type="button" class="close" phx-click="phx-modal-hide" aria-label="Close">
      <span aria-hidden="true">&times;</span>
    </button>
  </div>
  <div class="modal-body">
    Modal Content
  </div>
<% end %>

Here, modal is a helper function provided by Phoenix that generates the modal HTML.

Conclusion Creating and opening a modal in Phoenix 1.7 is a straightforward process that can be achieved using the phx-modal component. By following the steps outlined in this article, developers can add modals to their Phoenix apps and improve the user experience.