Logo

dev-resources.site

for different kinds of informations.

Bridging the Gap: Simplifying Live Component Invocation in Phoenix LiveView

Published at
12/4/2024
Categories
elixir
erlang
phoenix
liveview
Author
Herminio Torres
Categories
4 categories in total
elixir
open
erlang
open
phoenix
open
liveview
open
Bridging the Gap: Simplifying Live Component Invocation in Phoenix LiveView

Inspired by a conversation on Bsky (Thanks Netto) about the release of Phoenix LiveView 1.0.

The release of Phoenix LiveView 1.0 was announced yesterday! Hooorayyy! 🎉🥳

With numerous improvements aimed at simplifying the framework’s usage. One of the major enhancements stand out: the move from <%= %> to {} for rendering templates.

And I missed one more enhancements in terms of ergonomics when is calling components. Calling functional components in Phoenix LiveView is straightforward and seamless, making the developer experience intuitive. However, when dealing with live components, the syntax and approach differ significantly. This inconsistency can disrupt the ergonomics of the framework, especially for newcomers or teams striving for code simplicity and uniformity.

Here’s an example to ensure we’re on the same page and to illustrate the topic I’d like to explore further in this blog post.

Function Component

defmodule MyComponent do
  # In Phoenix apps, the line is typically: use MyAppWeb, :html
  use Phoenix.Component

  def greet(assigns) do
    ~H"""
    <p>Hello, {@name}!</p>
    """
  end
end
<MyComponent.greet name="Jane" />

Live Component

defmodule HeroComponent do
  # In Phoenix apps, the line is typically: use MyAppWeb, :live_component
  use Phoenix.LiveComponent

  def render(assigns) do
    ~H"""
    <div class="hero">{@content}</div>
    """
  end
end
<.live_component module={HeroComponent} id="hero" content={@content} />

I'll present a solution, hack—that bridges, enabling a more cohesive and developer-friendly way to invoke live components. By aligning the ergonomics of both functional and live components.

defmodule HeroComponent do
  # In Phoenix apps, the line is typically: use MyAppWeb, :live_component
  use Phoenix.LiveComponent

+  def call(assigns) do
+    ~H"""
+    <.live_component module={__MODULE__} {assigns}/>
+    """
+  end

  def render(assigns) do
    ~H"""
    <div class="hero">{@content}</div>
    """
  end
end

Here’s how you can call it:

<HeroComponent.call id="hero" content={@content} />

The next step for this implementation is to encapsulate it in a macro, allowing you to reuse it wherever needed.

Featured ones: