Feature

Reusable toggleable LiveView buttons

Preview

A lot of web apps need some sort of toggle buttons. So I have made a reusable toggleable LiveView buttons. As you can see they can have different kind of content and styling.

lib/phoenix_features_web/live/components/toggle_buttons_simple.ex
defmodule PhoenixFeaturesWeb.Components.ToggleButtonsSimple do
  use PhoenixFeaturesWeb, :live_component

  alias PhoenixFeaturesWeb.Components.ToggleButton

  def mount(socket) do
    {:ok,
      socket
      |> assign(:buttons, %{"toggle-text" => false, "toggle-star" => false, "toggle-lock" => true, "toggle-like" => true})
    }
  end

  def update(assigns, socket) do
    {:ok,
      socket
      |> assign(assigns)
    }
  end

  def handle_event("toggle-active", %{"button" => button}, socket) do
    button_state = !Map.get(socket.assigns.buttons, button, false)

    buttons =
      socket.assigns.buttons
      |> Map.put(button, button_state)

    {:noreply, assign(socket, buttons: buttons)}
  end
end