While searching and studying about live view I found this page of LiveComponent documentation, and reading more carefully about the “cost of a live component”, here: Phoenix.LiveComponent — Phoenix LiveView v0.18.18
Then it gives a not to do example, using a LiveComponent
to wrap DOM events, like:
defmodule MyButton do
use Phoenix.LiveComponent
def render(assigns) do
~H"""
<button class="css-framework-class" phx-click="click">
<%= @text %>
</button>
"""
end
def handle_event("click", _, socket) do
_ = socket.assigns.on_click.()
{:noreply, socket}
end
end
So it preferable to use a functional component! Then, it was I did! I have this function component to wrap and style the native DOM button tag:
attr :style, :string, values: ~w(primary secondary), required: true
attr :submit, :boolean, default: false
attr :icon, :atom, required: false, default: nil
attr :class, :string, default: ""
attr :rest, :global, doc: ~s(used for phoenix events like "phx-click" and "phx-target")
slot :inner_block
def button(assigns) do
~H"""
<button
type={if @submit, do: "submit", else: "button"}
class={["btn", "btn-#{@style}", @class]}
{@rest}
>
<.icon :if={@icon} name={@icon} />
<.text :if={@style == "primary"} size="base" color="text-white-100">
<%= render_slot(@inner_block) %>
</.text>
<.text :if={@style != "primary"} size="base" color="text-blue-80">
<%= render_slot(@inner_block) %>
</.text>
</button>
"""
end
To be reusable in any phoenix template with a predefined style. My question is, how this function component can handle events, in this case, phx-click
?
I used the button like this: pescarte-plataforma/show.html.heex at main · peapescarte/pescarte-plataforma · GitHub
However no event is trigged as can be seen in this little video: