phoenix-liveview-counter-tutorial
phoenix-liveview-counter-tutorial copied to clipboard
CSS file sent by the Phoenix app missing button color classes
After modifying the app by moving the code to a separate LiveView Component, as the tutorial suggests:
defmodule CounterComponent do
use Phoenix.LiveComponent
# Avoid duplicating Tailwind classes and show hot to inline a function call:
defp btn(color) do
"text-6xl pb-2 w-20 rounded-lg bg-#{color}-500 hover:bg-#{color}-600"
end
def render(assigns) do
~H"""
<div class="text-center">
<h1 class="text-4xl font-bold text-center"> Counter: <%= @val %> </h1>
<button phx-click="dec" class={btn("red")}>
-
</button>
<button phx-click="inc" class={btn("green")}>
+
</button>
</div>
"""
end
end
This also avoids some duplication by defining the common css in a helper function.
Unfortunately, this has a consequence: colors stop being rendered:
Inspecting HTML, the classes are being applied.
However, it turns out, definitions of bg-green-500 etc. are missing from the app.css file.
(Maybe it worked in older versions of Phoenix?)
After investigation I found this thread: https://elixirforum.com/t/phoenix-tailwind-not-producing-correct-css/46624
with explanation that this is due to the classes being computed dynamically.
Apparently the framework is not smart enough to deduce that such class will appear, and does not include it in rendered app.css.
One way to fix this is by including a comment in the HTML template with the full class names spelled out:
def render(assigns) do
~H"""
<div class="text-center">
<!-- bg-green-500 hover:bg-green-600 bg-red-500 hover:bg-red-600 -->
<h1 class="text-4xl font-bold text-center"> Counter: <%= @val %> </h1>
<button phx-click="dec" class={btn("red")}>-</button>
<button phx-click="inc" class={btn("green")}>+</button>
</div>
"""
end
Yeah. Stupid quirk with a stupid fix.