How to Create Nested LiveView Components
From ElixirBlocks
This example demonstrates a nested LiveView component.
defmodule AppxWeb.SandboxLive do
use AppxWeb, :live_view
import MyComponent
def mount(_params, _session, socket) do
{:ok, socket}
end
def render(assigns) do
~H"""
Hello World! YAY
<MyComponent.greet name="Jane" />
"""
end
end
defmodule MyComponent do use Phoenix.Component def greet(assigns) do ~H""" <p>Hello, <%= @name %>!</p> """ end end
An Example of a Button
defmodule AppWeb.PageLive do
use AppWeb, :live_view
def mount(_params, _session, socket) do
socket = assign(socket, count: 0)
{:ok, socket}
end
# Event handler in the parent LiveView
def handle_event("increment", _params, socket) do
{:noreply, assign(socket, count: socket.assigns.count + 1)}
end
def render(assigns) do
~H"""
<div class="container mx-auto p-4">
<h1 class="text-xl font-bold mb-4">Counter with Button Component</h1>
<div class="mb-4">
<p>Current count: <span class="font-bold"><%= @count %></span></p>
</div>
<.simple_button on_click="increment">
Increment Counter
</.simple_button>
</div>
"""
end
#_________________________________________________________BUTTON
# Simplified button component
def simple_button(assigns) do
~H"""
<button class="btn btn-lg" phx-click={@on_click} >
<%= render_slot(@inner_block) %>
</button>
"""
end
#___________________________________________________________END BUTTON
end