Skip to content

Svelte 5: Add class:list directive #12610

@brandonmcconnell

Description

@brandonmcconnell

Describe the problem

One of the most common packages many repos install once they pick up steam is clsx or a similar library to help manage their classes. While svelte already allows for easy CSS class name interpolation, a convention like clsx allows an even more flexible approach, filtering out nullish and boolean values, and preserving intended class names.

<!-- without clsx -->
<a class="staticClass {condition ? 'truthyClass' : 'falsyClass'}">…</a>

<!-- with clsx -->
<a class={clsx('staticClass', condition && 'truthyClass')}>…</a>

This is why…

  • over 4,000 different public svelte projects on GitHub alone also install clsx (proof 🍮)
  • nearly 1,000 different public svelte projects on GitHub alone also install classnames (proof 🍮)

Describe the proposed solution

Building this functionality into svelte directly using a directive like Astro's class:list directive would bring this capability to all svelte users, allowing svelte developers to add and manage classes more effectively, like this:

<!-- with class:list -->
<a class:list={['staticClass', condition && 'truthyClass']}>…</a>

Prior Art

Astro is the most recent and prominent prior art here, but users have been using clsx and others like it for years. This would provide a unified and built-in way to help manage classes for svelte developers.

Svelte has always been a "batteries included" framework, and I think the addition of a directive like this would follow that same trend.

Below is a list of all the issues I found related to Astro's implementation and refinement of class:list. That team started with a custom solution, but due to some gotchas, they ended up refactoring to build upon clsx itself.

Importance

would make my life easier

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions