@jcayzac/astro-classlist
TypeScript icon, indicating that this package has built-in type declarations

0.1.9 • Public • Published

@jcayzac/astro-classlist

Coerce Astro's class:list into an array of strings.

license npm version npm downloads bundle

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:

GitHub Sponsors Revolut Wise Ko-Fi PayPal


Package Sidebar

Install

npm i @jcayzac/astro-classlist

Weekly Downloads

7

Version

0.1.9

License

MIT

Unpacked Size

13.2 kB

Total Files

7

Last publish

Collaborators

  • jcayzac