elem-go icon indicating copy to clipboard operation
elem-go copied to clipboard

Add `ClassNames` utility function for conditional CSS class handling

Open chasefleming opened this issue 3 months ago • 0 comments

Problem

When conditionally applying CSS classes, developers currently need to manually concatenate strings and manage spacing, which is error-prone:

// Easy to mess up spacing
attrs.Props{
    attrs.Class: "btn" +
        elem.If(isPrimary, " btn-primary", "") +
        elem.If(isDisabled, " btn-disabled", ""),
}

// Forget a space? Broken CSS
attrs.Props{
    attrs.Class: "btn" + elem.If(isPrimary, "btn-primary", ""), // Missing space!
}

Proposed Solution

Add a ClassNames utility function to the attrs package that:

  • Joins multiple class name strings with spaces
  • Automatically filters out empty strings
  • Trims whitespace from class names
  • Uses strings.Builder for optimal performance

Usage Example

isPrimary := true
isDisabled := false

button := elem.Button(
    attrs.Props{
        attrs.Class: attrs.ClassNames(
            "btn",
            elem.If(isPrimary, "btn-primary", ""),
            elem.If(isDisabled, "btn-disabled", ""),
        ),
    },
    elem.Text("Submit"),
)
// Renders: <button class="btn btn-primary">Submit</button>

Implementation Notes

  • Should be added to attrs/utils.go
  • Needs comprehensive tests covering edge cases (empty strings, whitespace, etc.)
  • Should be documented in attrs/README.md

chasefleming avatar Oct 02 '25 13:10 chasefleming