View Source List

<List>

Presents rows of elements.

Overview

Each element inside the list is given its own row.

<List>
    <%= for sport <- @sports do %>
        <Text id={sport.id}><%= sport.name %></Text>
    <% end %>
</List>

Edit Mode

Use an <EditButton> to enter edit mode. This will allow rows to be moved, selected, and deleted.

<EditButton />
<List> ... </List>

Selecting Rows

Use the selection attribute to set the selected row(s).

<List selection={@selected_sports} phx-change="selection-changed">
    ...
</List>

Deleting and Moving Rows

Set an event name for the phx-delete attribute to enable the system delete action. An event is sent with the index of the item to delete.

<List phx-delete="on_delete">
    ...
</List>
defmodule MyAppWeb.SportsLive do
    def handle_event("on_delete", %{ "index" => index }, socket) do
        {:noreply, assign(socket, :items, List.delete_at(socket.assigns.items, index))}
    end
end

Use the phx-move event to enable the system move actions. An event is sent with the index of the item to move and its destination index.

<List phx-move="on_move">
    ...
</List>
defmodule MyAppWeb.SportsLive do
    def handle_event("on_move", %{ "index" => index, "destination" => destination }, socket) do
        {element, list} = List.pop_at(socket.assigns.sports, index)
        moved = List.insert_at(list, (if destination > index, do: destination - 1, else: destination), element)
        {:noreply, assign(socket, :sports, moved)}
    end
end

Attributes

Events

SwiftUI Documentation

See SwiftUI.List for more details on this View.

References

Event sent when a row is deleted.

Discussion

An event is sent with the index of the item to delete.

<List phx-delete="on_delete">
    ...
</List>
defmodule MyAppWeb.SportsLive do
    def handle_event("on_delete", %{ "index" => index }, socket) do
        {:noreply, assign(socket, :items, List.delete_at(socket.assigns.items, index))}
    end
end

Event sent when a row is moved.

Discussion

An event is sent with the index of the item to move and its destination index.

<List phx-move="on_move">
    ...
</List>
defmodule MyAppWeb.SportsLive do
    def handle_event("on_move", %{ "index" => index, "destination" => destination }, socket) do
        {element, list} = List.pop_at(socket.assigns.sports, index)
        moved = List.insert_at(list, (if destination > index, do: destination - 1, else: destination), element)
        {:noreply, assign(socket, :sports, moved)}
    end
end

Synchronizes the selected rows with the server.

Discussion

To allow an arbitrary number of rows to be selected, use the List type for the value. Use an empty list as the default value to start with no selection. To only allow a single selection, use the String type for the value. Use nil as the default value to start with no selection.