Building tailwind design system in React / Next.js

11-Jun-2023

Craete a typscript React / NextJs project with tailwindcss. Then install class-variance-authority inside project.

Generic badgeGeneric badgeGeneric badge

npm i class-variance-authority

scr/components/ui/button.tsx

import React from "react";
import { cva, type VariantProps } from "class-variance-authority";

const button = cva("button", {
  variants: {
    intent: {
      primary: [
        "bg-blue-500",
        "text-white",
        "border-transparent",
        "hover:bg-blue-600",
      ],
      secondary: [
        "bg-white",
        "text-gray-800",
        "border-gray-400",
        "hover:bg-gray-100",
      ],
    },
    size: {
      small: ["text-sm", "py-1", "px-2"],
      medium: ["text-base", "py-2", "px-4"],
    },
  },
  compoundVariants: [{ intent: "primary", size: "medium", class: "uppercase" }],
  defaultVariants: {
    intent: "primary",
    size: "medium",
  },
});

export interface ButtonProps
  extends React.ButtonHTMLAttributes<HTMLButtonElement>,
    VariantProps<typeof button> {}

export const Button: React.FC<ButtonProps> = ({
  className,
  intent,
  size,
  ...props
}) => <button className={button({ intent, size, className })} {...props} />;

When we can use Button component in our project

import { Button } from "./components/ui/button";

function App() {
  return (
    <div>
      <Button intent="primary" size="small">
        App Button
      </Button>
    </div>
  );
}

export default App;