badge.tsx


Overview

This file defines a reusable and customizable Badge React component that displays a small label or indicator with different visual styles (variants). The badge is styled using the class-variance-authority (CVA) utility to manage CSS class variants in a scalable and maintainable way.

The component is designed to be flexible, supporting multiple predefined style variants while allowing additional customization via standard HTML div attributes and extra CSS classes.


Exports


Detailed Explanations

badgeVariants

const badgeVariants = cva(
  'inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2',
  {
    variants: {
      variant: {
        default: 'border-transparent bg-primary text-primary-foreground hover:bg-primary/80',
        secondary: 'border-transparent bg-bg-card text-text-sub-title-invert hover:bg-secondary/80 rounded-md',
        destructive: 'border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80',
        outline: 'text-foreground',
      },
    },
    defaultVariants: {
      variant: 'default',
    },
  },
);

Usage: The badgeVariants function generates the appropriate CSS classes based on the variant selected.


BadgeProps Interface

export interface BadgeProps
  extends React.HTMLAttributes<HTMLDivElement>,
    VariantProps<typeof badgeVariants> {}

Badge Component

function Badge({ className, variant, ...props }: BadgeProps) {
  return (
    <div className={cn(badgeVariants({ variant }), className)} {...props} />
  );
}
<Badge>Default Badge</Badge>

<Badge variant="secondary">Secondary Badge</Badge>

<Badge variant="destructive" onClick={() => alert('Clicked!')}>
  Destructive Badge with Click Handler
</Badge>

<Badge variant="outline" className="custom-class">
  Outline Badge with Custom Class
</Badge>

Important Implementation Details


Interaction with Other Parts of the System


Visual Diagram

classDiagram
    class Badge {
        +BadgeProps props
        +render()
    }

    class badgeVariants {
        +variant: 'default' | 'secondary' | 'destructive' | 'outline'
        +generateClasses(variant)
    }

    Badge --> badgeVariants : uses
    Badge ..> React.HTMLAttributes : extends props
    Badge ..> VariantProps : extends props

Summary

The badge.tsx file exports a highly reusable, accessible, and style-variant enabled Badge component for React. It uses class-variance-authority for managing style variants and integrates seamlessly with Tailwind-like utility classes. The component is designed for flexibility and ease of use in the frontend UI to display labeled indicators with consistent styling and behavior.