# Badge (Caseroom component)

A short status or count next to text. Black and white, dark mode, shadcn-compatible; React, Astro and plain HTML.

1.4% of the 2,062 sites in The UI Index have a tag (28 sites).

## Install

- React: `npx shadcn@latest add https://www.themes.dev/caseroom/r/badge.json`
- Astro: `npx shadcn@latest add https://www.themes.dev/caseroom/r/astro/badge.json`
- HTML: https://www.themes.dev/caseroom/r/html/badge.html (with https://www.themes.dev/caseroom/r/html/caseroom.css)

Page: https://www.themes.dev/caseroom/components/badge/ · Rules for agents: https://www.themes.dev/caseroom/AGENT.md

## Code

### badge.astro

```astro
---
import type { HTMLAttributes } from 'astro/types';
import { cn } from '@/lib/utils';
import { badgeVariants, type BadgeVariants } from './badge.variants';

type Props = HTMLAttributes<'span'> & BadgeVariants;
const { variant, class: className, ...rest } = Astro.props;
---

<span class={cn(badgeVariants({ variant }), className)} {...rest}><slot /></span>
```

### badge.tsx

```tsx
import type { HTMLAttributes } from 'react';
import { cn } from '@/lib/utils';
import { badgeVariants, type BadgeVariants } from './badge.variants';

export type BadgeProps = HTMLAttributes<HTMLSpanElement> & BadgeVariants;

/** A short status or count. Not interactive: for a removable tag or a filter, use a button. */
export function Badge({ variant, className, ...props }: BadgeProps) {
  return <span className={cn(badgeVariants({ variant }), className)} {...props} />;
}

export { badgeVariants };
```

### badge.variants.ts

```tsx
import { cva, type VariantProps } from 'class-variance-authority';

export const badgeVariants = cva(
  'inline-flex w-fit shrink-0 items-center gap-1 rounded-sm border px-1.5 py-0.5 text-xs font-medium whitespace-nowrap [&_svg]:size-3',
  {
    variants: {
      variant: {
        // Foreground, not primary: a badge is a status, so an accent preset (which marks actions) leaves it alone.
        default: 'border-transparent bg-foreground text-background',
        secondary: 'border-transparent bg-secondary text-secondary-foreground',
        outline: 'border-border text-foreground',
        destructive: 'border-transparent bg-destructive text-destructive-foreground',
      },
    },
    defaultVariants: { variant: 'default' },
  },
);

export type BadgeVariants = VariantProps<typeof badgeVariants>;
```
