[]previous and next page

Button

Button in the Migrating from shadcn/ui and Radix guide.

For agentsUpdated

shadcn's Button is cva plus Slot. The port uses variants and Polymorphic, so as="a" replaces asChild.

src/ui/button.tsxtsx
import { splitProps } from "@shadow-js/core";
import {
  mergeElementProps,
  Polymorphic,
  type PolymorphicProps,
  type PolymorphicTarget,
} from "@shadow-js/primitives";
import type { JsxChild } from "@shadow-js/web";
import { variants } from "../lib/utils";

export const buttonVariants = variants(
  "inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50",
  {
    variants: {
      variant: {
        default: "bg-primary text-primary-foreground shadow hover:bg-primary/90",
        destructive: "bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90",
        outline: "border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground",
        secondary: "bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80",
        ghost: "hover:bg-accent hover:text-accent-foreground",
        link: "text-primary underline-offset-4 hover:underline",
      },
      size: {
        default: "h-9 px-4 py-2",
        sm: "h-8 rounded-md px-3 text-xs",
        lg: "h-10 rounded-md px-8",
        icon: "h-9 w-9",
      },
    },
    defaultVariants: { variant: "default", size: "default" },
  },
);

export interface ButtonOwnProps {
  readonly variant?: "default" | "destructive" | "outline" | "secondary" | "ghost" | "link" | undefined;
  readonly size?: "default" | "sm" | "lg" | "icon" | undefined;
}

export type ButtonProps<T extends PolymorphicTarget = "button"> = PolymorphicProps<"button", ButtonOwnProps, T>;

type Loose = ButtonOwnProps & { readonly as?: PolymorphicTarget; readonly [prop: string]: unknown };

export function Button<T extends PolymorphicTarget = "button">(props: ButtonProps<T>): JsxChild {
  const [own, rest] = splitProps(props as unknown as Loose, ["as", "variant", "size"]);
  const merged = mergeElementProps(
    {
      get class() {
        return buttonVariants({ variant: own.variant, size: own.size });
      },
    },
    rest,
  );
  return <Polymorphic as={own.as ?? "button"} {...merged} />;
}

export function ButtonDemo() {
  return (
    <Button variant="outline" size="sm" type="button">
      Cancel
    </Button>
  );
}