How do you set classes in heex?

I use sth like solid’s classList

<div class={class_list(%{
    "these classes are always included" => true,
    "these only when foo is 0" => @foo == 0,
    "only when bar aint baz" => @bar != "baz"
  })
}>
def class_list(map) do
  map
  |> Enum.filter(fn {_, include?} -> include? end)
  |> Enum.map(fn {class, _} -> class end)
  |> Enum.join(" ")
end

thats OK, but it would be nice if we could do

<div class_list={%{
    "these classes are always included" => true,
    "these only when foo is 0" => @foo == 0,
    "only when bar aint baz" => @bar != "baz"
  }}
>

What are some other approaches?

1 Like
<div class={[
    "these classes are always included",
    if(@foo == 0, do: "these only when foo is 0"),
    if(@bar != "baz", do: "only when bar aint baz")
  ]}
>
4 Likes

That’s also nice. Didn’t know you can give a list of strings. Where is this documented?

removing the join from the class_list function

https://hexdocs.pm/phoenix_live_view/0.18.6/Phoenix.Component.html#sigil_H/2-heex-extension-defining-attributes

3 Likes

this looks nice, I think I’ll settle with this. I knew there was sth hidden I did miss. Thank you.

<div class={[
    "these classes are always included",
    @foo == 0 && "these only when foo is 0",
    @bar != "baz" && "only when bar aint baz"
  ]}
>