Ethan Gunderson

TIL: Using Alpine.js with Phoenix Components

Phoenix 1.7, LiveView 0.18 introduces Phoenix.Components with declarative attributes. If you're upgrading an existing application that uses Alpine.js, you may run into compilation warnings that look something like

warning: undefined attribute "x-show" for component Phoenix.Component.form/1

Alpine.js directives are not declared attributes on components like Phoenix.Component.form, so their usage will cause the above compilation warning.

To work around this, we can use global attributes.

In your application web module add the following line to the view and component functions.

use Phoenix.Component, global_prefixes: ["x-"]

Then change the live_view function to be

def live_view do
    quote do
      use Phoenix.LiveView,
        layout: {GleanWeb.LayoutView, :live},
        global_prefixes: ["x-"]

      unquote(import_components())

      unquote(view_helpers())
    end
  end

Subscribe to my blog via email or RSS feed.

#til #phoenix #alpinejs

- 1 toast