DEV Community

Cover image for Bridging the Gap: Simplifying Live Component Invocation in Phoenix LiveView
Herminio Torres
Herminio Torres

Posted on

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
Enter fullscreen mode Exit fullscreen mode
<MyComponent.greet name="Jane" />
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode
<.live_component module={HeroComponent} id="hero" content={@content} />
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Here’s how you can call it:

<HeroComponent.call id="hero" content={@content} />
Enter fullscreen mode Exit fullscreen mode

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

Top comments (0)