@jcayzac/astro-classlist
v0.1.9
Published
Helper for Astro components to coerce `class:list` into an array of strings.
Downloads
16
Maintainers
Readme
@jcayzac/astro-classlist
Coerce Astro's
class:list
into an array of strings.
This module provides a single utility for Astro components, that coerce a value received as a class:list
prop into an array of strings.
You probably need this if your component receives a class:list
prop and passes it to a child component, and if you want to add other classes to the list.
Because class:list
can be an object or an iterable and contain things other than strings, it can get a bit messy if you want to add something to that.
// This is what you normally get from Astro
type AstroBuiltinAttributes['class:list'] =
| string
| Record<string, boolean>
| Record<any, any>
| Iterable<string>
| Iterable<any>
| undefined
// This is what you get when using this utility
type ClassList = string[]
Installation
# pnpm
pnpm add @jcayzac/astro-classlist
# bun
bunx add @jcayzac/astro-classlist
# npm
npx add @jcayzac/astro-classlist
# yarn
yarn add @jcayzac/astro-classlist
# deno
deno add npm:@jcayzac/astro-classlist
Usage
---
import type { AstroBuiltinAttributes } from 'astro'
import ChildComponent from '@components/ChildComponent.astro'
import { ClassList } from '@jcayzac/astro-classlist'
interface Props {
'class:list': AstroBuiltinAttributes['class:list']
}
const { 'class:list': classList } = Astro.props as Props
const classes: string[] = ClassList.toArray(classList)
---
<ChildComponent class:list={['mx-auto', ...classes]} />
Like it? Buy me a coffee!
If you like anything here, consider buying me a coffee using one of the following platforms: