Working with Sibling Components

From ElixirBlocks
Revision as of 13:59, 12 March 2025 by Admin (talk | contribs) (Created page with "<source> defmodule Heading do use Phoenix.Component def head(assigns) do ~H""" <ul> <%= for heading <- @headings do %> <li phx-click="append_content" phx-value-heading={heading}>{heading}!</li> <% end %> </ul> """ end end #________________________________________________________________ defmodule Content do use Phoenix.Component def content(assigns) do ~H""" <p>This is content: {@content}!</p> """ end end #__...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search
defmodule Heading do
  use Phoenix.Component

  def head(assigns) do
    ~H"""
    <ul>
      <%= for heading <- @headings do %>
        <li phx-click="append_content" phx-value-heading={heading}>{heading}!</li>
      <% end %>
    </ul>
    """
  end
end

#________________________________________________________________
defmodule Content do
  use Phoenix.Component

  def content(assigns) do
    ~H"""
    <p>This is content: {@content}!</p>
    """
  end
end
#________________________________________________________________

defmodule AppWeb.PageLive do
  use AppWeb, :live_view
  import Heading
  import Content

  def mount(_params, _session, socket) do
    {:ok, assign(socket, content: "This is some great content here")}
  end

  def headings do
    ["one", "two", "three"]
  end

  def render(assigns) do
    ~H"""
    <Heading.head headings={headings()} />
    <Content.content content={@content} />
    """
  end

  def handle_event("append_content", %{"heading" => _heading}, socket) do
    updated_content = socket.assigns.content <> " hello there"
    {:noreply, assign(socket, content: updated_content)}
  end
end