--- description: This guide defines definitive best practices for developing with shadcn/ui, ensuring consistent code organization, robust TypeScript, optimal performance, and accessible, maintainable components. globs: **/* --- # shadcn Best Practices This document outlines our team's definitive best practices for developing with `shadcn/ui`. Adhere to these guidelines for all `shadcn` component development and integration. ## 1. Code Organization and Structure Organize components logically to reflect UI hierarchy and promote discoverability. **Rule:** Place domain-specific components under `components/` and reusable UI primitives under `components/ui`. Each component must reside in its own PascalCase file. ❌ BAD: ``` // components/Button.tsx // components/profile-card.tsx // components/user-settings/index.tsx (contains multiple components) ``` ✅ GOOD: ``` // components/ui/Button.tsx // components/forms/DatePicker.tsx // components/layout/Sidebar.tsx // components/forms/index.ts export * from "./DatePicker"; export * from "./Input"; ``` ## 2. Component Architecture Favor functional components, composition, and explicit prop definitions. **Rule:** Use functional components with `React.forwardRef` and `asChild` for seamless integration with Radix primitives. ❌ BAD: ```tsx // No ref forwarding, no asChild const Button = ({ children, onClick }) => ( ); ``` ✅ GOOD: ```tsx // components/ui/Button.tsx import * as React from "react"; import { Slot } from "@radix-ui/react-slot"; import { cva, type VariantProps } from "class-variance-authority"; import { cn } from "@/lib/utils"; // Assuming you have a cn utility const buttonVariants = cva( "inline-flex items-center justify-center rounded-md text-sm font-medium", { variants: { variant: { default: "bg-primary text-primary-foreground hover:bg-primary/90", destructive: "bg-destructive text-destructive-foreground", }, size: { default: "h-10 px-4 py-2", sm: "h-9 rounded-md px-3", }, }, defaultVariants: { variant: "default", size: "default", }, } ); export interface ButtonProps extends React.ButtonHTMLAttributes, VariantProps { asChild?: boolean; } const Button = React.forwardRef( ({ className, variant, size, asChild = false, ...props }, ref) => { const Comp = asChild ? Slot : "button"; return ( ); } ); Button.displayName = "Button"; export { Button, buttonVariants }; ``` ## 3. TypeScript and API Design Enforce strict TypeScript with clear interfaces and robust validation. **Rule:** Use interfaces for component props. Validate form data with Zod schemas. Avoid `any` and prefer explicit types. ❌ BAD: ```typescript // Vague props, no validation type UserFormProps = { data: any; onSubmit: (values: any) => void; }; ``` ✅ GOOD: ```typescript // components/forms/UserForm.tsx import { z } from "zod"; export interface UserFormProps { initialData?: UserFormData; onSubmit: (values: UserFormData) => void; } export const userFormSchema = z.object({ id: z.string().optional(), name: z.string().min(2, "Name must be at least 2 characters."), email: z.string().email("Invalid email address."), }); export type UserFormData = z.infer; ``` ## 4. Theming and Styling Leverage Tailwind CSS and `class-variance-authority` (CVA) for consistent, maintainable styling. **Rule:** Define component variants using CVA. Use the `cn` utility for conditional class merging. Centralize Tailwind configuration and design tokens. ❌ BAD: ```tsx // Inconsistent inline styles or direct class manipulation {showChart && ( Loading chart...}> )} ); } ``` ## 7. Accessibility Build inclusive UIs by leveraging Radix primitives and ARIA attributes. **Rule:** Always use `shadcn/ui` components as they are built on Radix UI and provide excellent accessibility out-of-the-box. Ensure custom components correctly pass ARIA attributes and manage focus. ❌ BAD: ```tsx // Custom button without ARIA attributes or proper semantics
Click me
``` ✅ GOOD: ```tsx // Leverage shadcn/ui's accessible Button import { Button } from "@/components/ui/Button"; ``` ## 8. Common Pitfalls and Gotchas Avoid these common mistakes to maintain a scalable and robust codebase. **Rule:** Never directly modify `shadcn/ui` component files. Instead, extend them with `cn` or wrap them in higher-order components. Avoid `dangerouslySetInnerHTML`. ❌ BAD: ```tsx // Direct modification of a shadcn component (will be overwritten by CLI updates) // components/ui/button.tsx (modified directly) ``` ```tsx // Security vulnerability
``` ✅ GOOD: ```tsx // Extend with cn for custom styles import { Button } from "@/components/ui/Button"; ``` ```tsx // Sanitize and render text content safely import DOMPurify from 'dompurify'; const sanitizedContent = DOMPurify.sanitize(userProvidedContent); return
; // Or even better, avoid dangerouslySetInnerHTML if possible and render text directly // return

{userProvidedContent}

; ```