Badge
The Badge component is used to highlight and display statuses, labels, counts, or other small pieces of information.
Usage
<script>
import { Badge } from "$lib/components/ui/badge";
</script>
<Badge>New</Badge>
Examples
Default
The default badge style.
Variants
Different badge variants for different contexts.
With Icons
Badges with icons for enhanced visual cues.
Custom Styles
Custom badge styles using Tailwind classes.
Filmmaking Badges
Badge examples related to filmmaking in magic.mov.
With Counts
Badges used to display numeric values or counts.
API Reference
Badge Properties
Property | Type | Default | Description |
---|---|---|---|
variant | "default" \| "secondary" \| "destructive" \| "outline" | "default" | The visual style of the badge. |
href | string | undefined | If provided, the badge will render as an anchor element with this URL. |
class | string | undefined | Custom CSS classes. |
ref | HTMLElement | undefined | A reference to the underlying HTML element. |
Badge Variants
Variant | Description |
---|---|
default | Primary style with filled background. |
secondary | Secondary style with muted background. |
destructive | Red style for destructive or error states. |
outline | Outlined style with transparent background. |
Using badgeVariants
The badgeVariants
function can be used to apply badge styles to other elements:
<script>
import { badgeVariants } from "$lib/components/ui/badge";
</script>
<div class={badgeVariants({ variant: "default" })}>
Custom Element with Badge Styles
</div>
Implementation
The Badge component is implemented using a flexible design that renders either a span
or an a
element depending on whether the href
prop is provided:
<script lang="ts" module>
import { type VariantProps, tv } from "tailwind-variants";
export const badgeVariants = tv({
base: "focus:ring-ring inline-flex select-none items-center rounded-md border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-offset-2",
variants: {
variant: {
default:
"bg-primary text-primary-foreground hover:bg-primary/80 border-transparent shadow",
secondary:
"bg-secondary text-secondary-foreground hover:bg-secondary/80 border-transparent",
destructive:
"bg-destructive text-destructive-foreground hover:bg-destructive/80 border-transparent shadow",
outline: "text-foreground",
},
},
defaultVariants: {
variant: "default",
},
});
</script>
<svelte:element
this={href ? "a" : "span"}
bind:this={ref}
{href}
class={cn(badgeVariants({ variant, className }))}
{...restProps}
>
{@render children?.()}
</svelte:element>
The component uses Tailwind Variants (tv
) to define and manage the different style variants, making it easy to maintain and extend the component’s styles.