Phoenix conditional class shorthand

Published on

When working with Phoenix LiveView it’s possible to use a shorthand for multiple conditional classes. Take the following component as an example.

defmodule AppWeb.Component do
  use Phoenix.Component
  
  def example_component(assigns) do
    assigns = assign(assigns, 
                red: true,
                green: false
              )

    # This can be useful when you have a lot of possible configurations for your component.
    assigns = assign(assigns,
                class: [
                "font-semibold",
                assigns.red && "text-red-500",
                assigns.green && "text-green-500"
              ])

    ~H"""
    <div class={@class}>
      Some component
    </div>
    """
  end
end