Class Template Directive in Astro
Astro is an open-source front-end framework that leverages modern web standards for fast, optimized, and maintainable website development. It separates content from presentation, enhancing SEO and accessibility, while allowing integration of popular libraries such as React, Vue, Svelte, or HTML/CSS.
As I refactor code into reusable components often I run into a case where I prefer to have property driven styling for the component.
Astro has a built-in directive (class:list) meant for taking in arrays, sets, objects, strings, and more. Whatever array you pass in is flattened and added in the class attribute.
Syntax
Astro’s class:list={…} template directive “takes an array of class values and converts them into a class string.”
class:list takes an array of several different possible value kinds:
string: Added to the elementclassObject: All truthy keys are added to the elementclassArray: flattenedfalse,null, orundefined: skipped
Any duplicate values are removed automatically.
Example
<!-- this 👇🏽 -->
<div
class:list={[
"wrapper",
{ "info-wrapper": isInfo,
"alert-wrapper": !isInfo
}
]}
>
...
</div>
<!-- rendered as 👇🏽 for isInfo = true-->
<div class="wrapper info-wrapper">
...
</div>
Reference: Astro Template Directives Documentation