TIL: How to use `class_variants` with Phlex
Feb 15, 2025
With Phlex hitting the next major version I decided to try it out and see how I would like it compared to ViewComponents.
I have been using ViewComponents since its first release and since then I have found or added utilities to my toolbelt. One of those is view_component-contrib
which has a CVA (Class Variance Authority) implementation.
Luckily Avo have create the class_variants
gem. Which is super easy to use in Phlex.
module Components
class Base < Phlex::HTML
# ... other includes
include ClassVariants::Helper
end
end
# Then in another component do this
module Components
class AnotherThing < Base
def view_template(&)
div(class: class_variants(border: true), &)
end
class_variants do
base 'rounded-md shadow-md font-semibold ...other classes here.'
variant :border, 'border border-grey-200'
end
end
end
And thats it, have fun…