xonecas.io
556
Bn

bees-nest / files

bees-nest / .opencode / skills / shadcn-ui / SKILL.md

37.8 KB
1---
2name: shadcn-ui
3description: Complete shadcn/ui component library guide including installation, configuration, and implementation of accessible React components. Use when setting up shadcn/ui, installing components, building forms with React Hook Form and Zod, customizing themes with Tailwind CSS, or implementing UI patterns like buttons, dialogs, dropdowns, tables, and complex form layouts.
4language: typescript,tsx
5framework: react,nextjs,tailwindcss
6license: MIT
7allowed-tools: Read, Write, Bash, Edit, Glob
8---
9
10# shadcn/ui Component Patterns
11
12Expert guide for building accessible, customizable UI components with shadcn/ui, Radix UI, and Tailwind CSS.
13
14## Table of Contents
15
16- [When to Use](#when-to-use)
17- [Quick Start](#quick-start)
18- [Installation & Setup](#installation--setup)
19- [Project Configuration](#project-configuration)
20- [Core Components](#core-components)
21  - [Button](#button-component)
22  - [Input & Form Fields](#input--form-fields)
23  - [Forms with Validation](#forms-with-validation)
24  - [Card](#card-component)
25  - [Dialog (Modal)](#dialog-modal-component)
26  - [Select (Dropdown)](#select-dropdown-component)
27  - [Sheet (Slide-over)](#sheet-slide-over-component)
28  - [Menubar & Navigation](#menubar--navigation)
29  - [Table](#table-component)
30  - [Toast Notifications](#toast-notifications)
31- [Advanced Patterns](#advanced-patterns)
32- [Customization](#customization)
33- [Next.js Integration](#nextjs-integration)
34- [Best Practices](#best-practices)
35- [Common Component Combinations](#common-component-combinations)
36
37## When to Use
38
39- Setting up a new project with shadcn/ui
40- Installing or configuring individual components
41- Building forms with React Hook Form and Zod validation
42- Creating accessible UI components (buttons, dialogs, dropdowns, sheets)
43- Customizing component styling with Tailwind CSS
44- Implementing design systems with shadcn/ui
45- Building Next.js applications with TypeScript
46- Creating complex layouts and data displays
47
48## Quick Start
49
50For new projects, use the automated setup:
51
52```bash
53# Create Next.js project with shadcn/ui
54npx create-next-app@latest my-app --typescript --tailwind --eslint --app
55cd my-app
56npx shadcn@latest init
57
58# Install essential components
59npx shadcn@latest add button input form card dialog select
60```
61
62For existing projects:
63
64```bash
65# Install dependencies
66npm install tailwindcss-animate class-variance-authority clsx tailwind-merge lucide-react
67
68# Initialize shadcn/ui
69npx shadcn@latest init
70```
71
72## What is shadcn/ui?
73
74shadcn/ui is **not** a traditional component library or npm package. Instead:
75
76- It's a **collection of reusable components** that you can copy into your project
77- Components are **yours to customize** - you own the code
78- Built with **Radix UI** primitives for accessibility
79- Styled with **Tailwind CSS** utilities
80- Includes CLI tool for easy component installation
81
82## Installation & Setup
83
84### Initial Setup
85
86```bash
87# Initialize shadcn/ui in your project
88npx shadcn@latest init
89```
90
91During setup, you'll configure:
92- TypeScript or JavaScript
93- Style (Default, New York, etc.)
94- Base color theme
95- CSS variables or Tailwind CSS classes
96- Component installation path
97
98### Installing Individual Components
99
100```bash
101# Install a single component
102npx shadcn@latest add button
103
104# Install multiple components
105npx shadcn@latest add button input form
106
107# Install all components
108npx shadcn@latest add --all
109```
110
111### Manual Installation
112
113If you prefer manual setup:
114
115```bash
116# Install dependencies for a specific component
117npm install @radix-ui/react-slot
118
119# Copy component code from ui.shadcn.com
120# Place in src/components/ui/
121```
122
123## Project Configuration
124
125### Required Dependencies
126
127```json
128{
129  "dependencies": {
130    "@radix-ui/react-accordion": "^1.1.2",
131    "@radix-ui/react-alert-dialog": "^1.0.5",
132    "@radix-ui/react-dialog": "^1.0.5",
133    "@radix-ui/react-dropdown-menu": "^2.0.6",
134    "@radix-ui/react-label": "^2.0.2",
135    "@radix-ui/react-select": "^2.0.0",
136    "@radix-ui/react-separator": "^1.0.3",
137    "@radix-ui/react-slot": "^1.0.2",
138    "@radix-ui/react-toast": "^1.1.5",
139    "class-variance-authority": "^0.7.0",
140    "clsx": "^2.0.0",
141    "lucide-react": "^0.294.0",
142    "tailwind-merge": "^2.0.0",
143    "tailwindcss-animate": "^1.0.7"
144  }
145}
146```
147
148### TSConfig Configuration
149
150```json
151{
152  "compilerOptions": {
153    "target": "es5",
154    "lib": ["dom", "dom.iterable", "es6"],
155    "allowJs": true,
156    "skipLibCheck": true,
157    "strict": true,
158    "forceConsistentCasingInFileNames": true,
159    "noEmit": true,
160    "esModuleInterop": true,
161    "module": "esnext",
162    "moduleResolution": "node",
163    "resolveJsonModule": true,
164    "isolatedModules": true,
165    "jsx": "preserve",
166    "incremental": true,
167    "plugins": [
168      {
169        "name": "next"
170      }
171    ],
172    "baseUrl": ".",
173    "paths": {
174      "@/components/*": ["./src/components/*"],
175      "@/lib/*": ["./src/lib/*"]
176    }
177  },
178  "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
179  "exclude": ["node_modules"]
180}
181```
182
183### Tailwind Configuration
184
185```js
186// tailwind.config.js
187/** @type {import('tailwindcss').Config} */
188module.exports = {
189  darkMode: ["class"],
190  content: [
191    './pages/**/*.{ts,tsx}',
192    './components/**/*.{ts,tsx}',
193    './app/**/*.{ts,tsx}',
194    './src/**/*.{ts,tsx}',
195  ],
196  prefix: "",
197  theme: {
198    container: {
199      center: true,
200      padding: "2rem",
201      screens: {
202        "2xl": "1400px",
203      },
204    },
205    extend: {
206      colors: {
207        border: "hsl(var(--border))",
208        input: "hsl(var(--input))",
209        ring: "hsl(var(--ring))",
210        background: "hsl(var(--background))",
211        foreground: "hsl(var(--foreground))",
212        primary: {
213          DEFAULT: "hsl(var(--primary))",
214          foreground: "hsl(var(--primary-foreground))",
215        },
216        secondary: {
217          DEFAULT: "hsl(var(--secondary))",
218          foreground: "hsl(var(--secondary-foreground))",
219        },
220        destructive: {
221          DEFAULT: "hsl(var(--destructive))",
222          foreground: "hsl(var(--destructive-foreground))",
223        },
224        muted: {
225          DEFAULT: "hsl(var(--muted))",
226          foreground: "hsl(var(--muted-foreground))",
227        },
228        accent: {
229          DEFAULT: "hsl(var(--accent))",
230          foreground: "hsl(var(--accent-foreground))",
231        },
232        popover: {
233          DEFAULT: "hsl(var(--popover))",
234          foreground: "hsl(var(--popover-foreground))",
235        },
236        card: {
237          DEFAULT: "hsl(var(--card))",
238          foreground: "hsl(var(--card-foreground))",
239        },
240      },
241      borderRadius: {
242        lg: "var(--radius)",
243        md: "calc(var(--radius) - 2px)",
244        sm: "calc(var(--radius) - 4px)",
245      },
246      keyframes: {
247        "accordion-down": {
248          from: { height: "0" },
249          to: { height: "var(--radix-accordion-content-height)" },
250        },
251        "accordion-up": {
252          from: { height: "var(--radix-accordion-content-height)" },
253          to: { height: "0" },
254        },
255      },
256      animation: {
257        "accordion-down": "accordion-down 0.2s ease-out",
258        "accordion-up": "accordion-up 0.2s ease-out",
259      },
260    },
261  },
262  plugins: [require("tailwindcss-animate")],
263}
264```
265
266### CSS Variables (globals.css)
267
268```css
269@tailwind base;
270@tailwind components;
271@tailwind utilities;
272
273@layer base {
274  :root {
275    --background: 0 0% 100%;
276    --foreground: 222.2 84% 4.9%;
277    --card: 0 0% 100%;
278    --card-foreground: 222.2 84% 4.9%;
279    --popover: 0 0% 100%;
280    --popover-foreground: 222.2 84% 4.9%;
281    --primary: 222.2 47.4% 11.2%;
282    --primary-foreground: 210 40% 98%;
283    --secondary: 210 40% 96.1%;
284    --secondary-foreground: 222.2 47.4% 11.2%;
285    --muted: 210 40% 96.1%;
286    --muted-foreground: 215.4 16.3% 46.9%;
287    --accent: 210 40% 96.1%;
288    --accent-foreground: 222.2 47.4% 11.2%;
289    --destructive: 0 84.2% 60.2%;
290    --destructive-foreground: 210 40% 98%;
291    --border: 214.3 31.8% 91.4%;
292    --input: 214.3 31.8% 91.4%;
293    --ring: 222.2 84% 4.9%;
294    --radius: 0.5rem;
295  }
296
297  .dark {
298    --background: 222.2 84% 4.9%;
299    --foreground: 210 40% 98%;
300    --card: 222.2 84% 4.9%;
301    --card-foreground: 210 40% 98%;
302    --popover: 222.2 84% 4.9%;
303    --popover-foreground: 210 40% 98%;
304    --primary: 210 40% 98%;
305    --primary-foreground: 222.2 47.4% 11.2%;
306    --secondary: 217.2 32.6% 17.5%;
307    --secondary-foreground: 210 40% 98%;
308    --muted: 217.2 32.6% 17.5%;
309    --muted-foreground: 215 20.2% 65.1%;
310    --accent: 217.2 32.6% 17.5%;
311    --accent-foreground: 210 40% 98%;
312    --destructive: 0 62.8% 30.6%;
313    --destructive-foreground: 210 40% 98%;
314    --border: 217.2 32.6% 17.5%;
315    --input: 217.2 32.6% 17.5%;
316    --ring: 212.7 26.8% 83.9%;
317  }
318}
319
320@layer base {
321  * {
322    @apply border-border;
323  }
324  body {
325    @apply bg-background text-foreground;
326  }
327}
328```
329
330## Core Components
331
332### Button Component
333
334Installation:
335
336```bash
337npx shadcn@latest add button
338```
339
340Basic usage:
341
342```tsx
343import { Button } from "@/components/ui/button";
344
345export function ButtonDemo() {
346  return <Button>Click me</Button>;
347}
348```
349
350Button variants:
351
352```tsx
353import { Button } from "@/components/ui/button";
354
355export function ButtonVariants() {
356  return (
357    <div className="flex gap-4">
358      <Button variant="default">Default</Button>
359      <Button variant="destructive">Destructive</Button>
360      <Button variant="outline">Outline</Button>
361      <Button variant="secondary">Secondary</Button>
362      <Button variant="ghost">Ghost</Button>
363      <Button variant="link">Link</Button>
364    </div>
365  );
366}
367```
368
369Button sizes:
370
371```tsx
372<div className="flex gap-4 items-center">
373  <Button size="default">Default</Button>
374  <Button size="sm">Small</Button>
375  <Button size="lg">Large</Button>
376  <Button size="icon">
377    <Icon className="h-4 w-4" />
378  </Button>
379</div>
380```
381
382With loading state:
383
384```tsx
385import { Button } from "@/components/ui/button";
386import { Loader2 } from "lucide-react";
387
388export function ButtonLoading() {
389  return (
390    <Button disabled>
391      <Loader2 className="mr-2 h-4 w-4 animate-spin" />
392      Please wait
393    </Button>
394  );
395}
396```
397
398### Input & Form Fields
399
400#### Input Component
401
402Installation:
403
404```bash
405npx shadcn@latest add input
406```
407
408Basic input:
409
410```tsx
411import { Input } from "@/components/ui/input";
412
413export function InputDemo() {
414  return <Input type="email" placeholder="Email" />;
415}
416```
417
418Input with label:
419
420```tsx
421import { Input } from "@/components/ui/input";
422import { Label } from "@/components/ui/label";
423
424export function InputWithLabel() {
425  return (
426    <div className="grid w-full max-w-sm items-center gap-1.5">
427      <Label htmlFor="email">Email</Label>
428      <Input type="email" id="email" placeholder="Email" />
429    </div>
430  );
431}
432```
433
434Input with button:
435
436```tsx
437import { Button } from "@/components/ui/button";
438import { Input } from "@/components/ui/input";
439
440export function InputWithButton() {
441  return (
442    <div className="flex w-full max-w-sm items-center gap-2">
443      <Input type="email" placeholder="Email" />
444      <Button type="submit" variant="outline">Subscribe</Button>
445    </div>
446  );
447}
448```
449
450### Forms with Validation
451
452Installation:
453
454```bash
455npx shadcn@latest add form
456```
457
458This installs React Hook Form, Zod, and form components.
459
460Complete form example:
461
462```tsx
463"use client"
464
465import { zodResolver } from "@hookform/resolvers/zod"
466import { useForm } from "react-hook-form"
467import * as z from "zod"
468
469import { Button } from "@/components/ui/button"
470import {
471  Form,
472  FormControl,
473  FormDescription,
474  FormField,
475  FormItem,
476  FormLabel,
477  FormMessage,
478} from "@/components/ui/form"
479import { Input } from "@/components/ui/input"
480import { toast } from "@/components/ui/use-toast"
481
482const formSchema = z.object({
483  username: z.string().min(2, {
484    message: "Username must be at least 2 characters.",
485  }),
486  email: z.string().email({
487    message: "Please enter a valid email address.",
488  }),
489})
490
491export function ProfileForm() {
492  const form = useForm<z.infer<typeof formSchema>>({
493    resolver: zodResolver(formSchema),
494    defaultValues: {
495      username: "",
496      email: "",
497    },
498  })
499
500  function onSubmit(values: z.infer<typeof formSchema>) {
501    toast({
502      title: "You submitted the following values:",
503      description: (
504        <pre className="mt-2 w-[340px] rounded-md bg-slate-950 p-4">
505          <code className="text-white">{JSON.stringify(values, null, 2)}</code>
506        </pre>
507      ),
508    })
509  }
510
511  return (
512    <Form {...form}>
513      <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-8">
514        <FormField
515          control={form.control}
516          name="username"
517          render={({ field }) => (
518            <FormItem>
519              <FormLabel>Username</FormLabel>
520              <FormControl>
521                <Input placeholder="shadcn" {...field} />
522              </FormControl>
523              <FormDescription>
524                This is your public display name.
525              </FormDescription>
526              <FormMessage />
527            </FormItem>
528          )}
529        />
530        
531        <FormField
532          control={form.control}
533          name="email"
534          render={({ field }) => (
535            <FormItem>
536              <FormLabel>Email</FormLabel>
537              <FormControl>
538                <Input type="email" placeholder="you@example.com" {...field} />
539              </FormControl>
540              <FormMessage />
541            </FormItem>
542          )}
543        />
544        
545        <Button type="submit">Submit</Button>
546      </form>
547    </Form>
548  )
549}
550```
551
552### Card Component
553
554Installation:
555
556```bash
557npx shadcn@latest add card
558```
559
560Basic card:
561
562```tsx
563import {
564  Card,
565  CardContent,
566  CardDescription,
567  CardFooter,
568  CardHeader,
569  CardTitle,
570} from "@/components/ui/card"
571
572export function CardDemo() {
573  return (
574    <Card>
575      <CardHeader>
576        <CardTitle>Card Title</CardTitle>
577        <CardDescription>Card Description</CardDescription>
578      </CardHeader>
579      <CardContent>
580        <p>Card Content</p>
581      </CardContent>
582      <CardFooter>
583        <p>Card Footer</p>
584      </CardFooter>
585    </Card>
586  )
587}
588```
589
590Card with form:
591
592```tsx
593import { Button } from "@/components/ui/button"
594import {
595  Card,
596  CardContent,
597  CardDescription,
598  CardFooter,
599  CardHeader,
600  CardTitle,
601} from "@/components/ui/card"
602import { Input } from "@/components/ui/input"
603import { Label } from "@/components/ui/label"
604
605export function CardWithForm() {
606  return (
607    <Card className="w-[350px]">
608      <CardHeader>
609        <CardTitle>Create project</CardTitle>
610        <CardDescription>Deploy your new project in one-click.</CardDescription>
611      </CardHeader>
612      <CardContent>
613        <form>
614          <div className="grid w-full items-center gap-4">
615            <div className="flex flex-col space-y-1.5">
616              <Label htmlFor="name">Name</Label>
617              <Input id="name" placeholder="Name of your project" />
618            </div>
619          </div>
620        </form>
621      </CardContent>
622      <CardFooter className="flex justify-between">
623        <Button variant="outline">Cancel</Button>
624        <Button>Deploy</Button>
625      </CardFooter>
626    </Card>
627  )
628}
629```
630
631### Dialog (Modal) Component
632
633Installation:
634
635```bash
636npx shadcn@latest add dialog
637```
638
639Basic dialog:
640
641```tsx
642import { Button } from "@/components/ui/button"
643import {
644  Dialog,
645  DialogContent,
646  DialogDescription,
647  DialogFooter,
648  DialogHeader,
649  DialogTitle,
650  DialogTrigger,
651} from "@/components/ui/dialog"
652
653export function DialogDemo() {
654  return (
655    <Dialog>
656      <DialogTrigger asChild>
657        <Button variant="outline">Open Dialog</Button>
658      </DialogTrigger>
659      <DialogContent className="sm:max-w-[425px]">
660        <DialogHeader>
661          <DialogTitle>Edit profile</DialogTitle>
662          <DialogDescription>
663            Make changes to your profile here. Click save when you're done.
664          </DialogDescription>
665        </DialogHeader>
666        <div className="grid gap-4 py-4">
667          <div className="grid grid-cols-4 items-center gap-4">
668            <Label htmlFor="name" className="text-right">
669              Name
670            </Label>
671            <Input id="name" value="Pedro Duarte" className="col-span-3" />
672          </div>
673        </div>
674        <DialogFooter>
675          <Button type="submit">Save changes</Button>
676        </DialogFooter>
677      </DialogContent>
678    </Dialog>
679  )
680}
681```
682
683### Sheet (Slide-over) Component
684
685Installation:
686
687```bash
688npx shadcn@latest add sheet
689```
690
691Basic sheet:
692
693```tsx
694import { Button } from "@/components/ui/button"
695import {
696  Sheet,
697  SheetContent,
698  SheetDescription,
699  SheetHeader,
700  SheetTitle,
701  SheetTrigger,
702} from "@/components/ui/sheet"
703
704export function SheetDemo() {
705  return (
706    <Sheet>
707      <SheetTrigger asChild>
708        <Button variant="outline">Open Sheet</Button>
709      </SheetTrigger>
710      <SheetContent>
711        <SheetHeader>
712          <SheetTitle>Edit profile</SheetTitle>
713          <SheetDescription>
714            Make changes to your profile here. Click save when you're done.
715          </SheetDescription>
716        </SheetHeader>
717        <div className="grid gap-4 py-4">
718          <div className="grid grid-cols-4 items-center gap-4">
719            <Label htmlFor="name" className="text-right">
720              Name
721            </Label>
722            <Input id="name" value="Pedro Duarte" className="col-span-3" />
723          </div>
724          <div className="grid grid-cols-4 items-center gap-4">
725            <Label htmlFor="username" className="text-right">
726              Username
727            </Label>
728            <Input id="username" value="@peduarte" className="col-span-3" />
729          </div>
730        </div>
731      </SheetContent>
732    </Sheet>
733  )
734}
735```
736
737Sheet with side placement:
738
739```tsx
740<Sheet>
741  <SheetTrigger asChild>
742    <Button variant="outline">Open Right Sheet</Button>
743  </SheetTrigger>
744  <SheetContent side="right">
745    <SheetHeader>
746      <SheetTitle>Settings</SheetTitle>
747      <SheetDescription>
748        Configure your application settings here.
749      </SheetDescription>
750    </SheetHeader>
751    {/* Settings content */}
752  </SheetContent>
753</Sheet>
754```
755
756### Menubar & Navigation
757
758#### Menubar Component
759
760Installation:
761
762```bash
763npx shadcn@latest add menubar
764```
765
766Basic menubar:
767
768```tsx
769import {
770  Menubar,
771  MenubarContent,
772  MenubarItem,
773  MenubarMenu,
774  MenubarSeparator,
775  MenubarShortcut,
776  MenubarSub,
777  MenubarSubContent,
778  MenubarSubTrigger,
779  MenubarTrigger,
780} from "@/components/ui/menubar"
781
782export function MenubarDemo() {
783  return (
784    <Menubar>
785      <MenubarMenu>
786        <MenubarTrigger>File</MenubarTrigger>
787        <MenubarContent>
788          <MenubarItem>
789            New Tab <MenubarShortcut>⌘T</MenubarShortcut>
790          </MenubarItem>
791          <MenubarItem>
792            New Window <MenubarShortcut>⌘N</MenubarShortcut>
793          </MenubarItem>
794          <MenubarSeparator />
795          <MenubarItem>Share</MenubarItem>
796          <MenubarSeparator />
797          <MenubarItem>Print</MenubarItem>
798        </MenubarContent>
799      </MenubarMenu>
800      <MenubarMenu>
801        <MenubarTrigger>Edit</MenubarTrigger>
802        <MenubarContent>
803          <MenubarItem>
804            Undo <MenubarShortcut>⌘Z</MenubarShortcut>
805          </MenubarItem>
806          <MenubarItem>
807            Redo <MenubarShortcut>⌘Y</MenubarShortcut>
808          </MenubarItem>
809          <MenubarSeparator />
810          <MenubarSub>
811            <MenubarSubTrigger>Find</MenubarSubTrigger>
812            <MenubarSubContent>
813              <MenubarItem>Search the web</MenubarItem>
814              <MenubarItem>Find...</MenubarItem>
815              <MenubarItem>Find Next</MenubarItem>
816              <MenubarItem>Find Previous</MenubarItem>
817            </MenubarSubContent>
818          </MenubarSub>
819        </MenubarContent>
820      </MenubarMenu>
821    </Menubar>
822  )
823}
824```
825
826### Select (Dropdown) Component
827
828Installation:
829
830```bash
831npx shadcn@latest add select
832```
833
834Basic select:
835
836```tsx
837import {
838  Select,
839  SelectContent,
840  SelectItem,
841  SelectTrigger,
842  SelectValue,
843} from "@/components/ui/select"
844
845export function SelectDemo() {
846  return (
847    <Select>
848      <SelectTrigger className="w-[180px]">
849        <SelectValue placeholder="Select a fruit" />
850      </SelectTrigger>
851      <SelectContent>
852        <SelectItem value="apple">Apple</SelectItem>
853        <SelectItem value="banana">Banana</SelectItem>
854        <SelectItem value="orange">Orange</SelectItem>
855      </SelectContent>
856    </Select>
857  )
858}
859```
860
861Select in form:
862
863```tsx
864<FormField
865  control={form.control}
866  name="role"
867  render={({ field }) => (
868    <FormItem>
869      <FormLabel>Role</FormLabel>
870      <Select onValueChange={field.onChange} defaultValue={field.value}>
871        <FormControl>
872          <SelectTrigger>
873            <SelectValue placeholder="Select a role" />
874          </SelectTrigger>
875        </FormControl>
876        <SelectContent>
877          <SelectItem value="admin">Admin</SelectItem>
878          <SelectItem value="user">User</SelectItem>
879          <SelectItem value="guest">Guest</SelectItem>
880        </SelectContent>
881      </Select>
882      <FormMessage />
883    </FormItem>
884  )}
885/>
886```
887
888### Toast Notifications
889
890Installation:
891
892```bash
893npx shadcn@latest add toast
894```
895
896Setup toast provider in root layout:
897
898```tsx
899import { Toaster } from "@/components/ui/toaster"
900
901export default function RootLayout({ children }) {
902  return (
903    <html lang="en">
904      <body>
905        {children}
906        <Toaster />
907      </body>
908    </html>
909  )
910}
911```
912
913Using toast:
914
915```tsx
916import { useToast } from "@/components/ui/use-toast"
917import { Button } from "@/components/ui/button"
918
919export function ToastDemo() {
920  const { toast } = useToast()
921
922  return (
923    <Button
924      onClick={() => {
925        toast({
926          title: "Scheduled: Catch up",
927          description: "Friday, February 10, 2023 at 5:57 PM",
928        })
929      }}
930    >
931      Show Toast
932    </Button>
933  )
934}
935```
936
937Toast variants:
938
939```tsx
940// Success
941toast({
942  title: "Success",
943  description: "Your changes have been saved.",
944})
945
946// Error
947toast({
948  variant: "destructive",
949  title: "Error",
950  description: "Something went wrong.",
951})
952
953// With action
954toast({
955  title: "Uh oh! Something went wrong.",
956  description: "There was a problem with your request.",
957  action: <ToastAction altText="Try again">Try again</ToastAction>,
958})
959```
960
961### Table Component
962
963Installation:
964
965```bash
966npx shadcn@latest add table
967```
968
969Basic table:
970
971```tsx
972import {
973  Table,
974  TableBody,
975  TableCaption,
976  TableCell,
977  TableHead,
978  TableHeader,
979  TableRow,
980} from "@/components/ui/table"
981
982const invoices = [
983  { invoice: "INV001", status: "Paid", method: "Credit Card", amount: "$250.00" },
984  { invoice: "INV002", status: "Pending", method: "PayPal", amount: "$150.00" },
985]
986
987export function TableDemo() {
988  return (
989    <Table>
990      <TableCaption>A list of your recent invoices.</TableCaption>
991      <TableHeader>
992        <TableRow>
993          <TableHead>Invoice</TableHead>
994          <TableHead>Status</TableHead>
995          <TableHead>Method</TableHead>
996          <TableHead className="text-right">Amount</TableHead>
997        </TableRow>
998      </TableHeader>
999      <TableBody>
1000        {invoices.map((invoice) => (
1001          <TableRow key={invoice.invoice}>
1002            <TableCell className="font-medium">{invoice.invoice}</TableCell>
1003            <TableCell>{invoice.status}</TableCell>
1004            <TableCell>{invoice.method}</TableCell>
1005            <TableCell className="text-right">{invoice.amount}</TableCell>
1006          </TableRow>
1007        ))}
1008      </TableBody>
1009    </Table>
1010  )
1011}
1012```
1013
1014## Customization
1015
1016### Theming with CSS Variables
1017
1018shadcn/ui uses CSS variables for theming. Configure in `globals.css`:
1019
1020```css
1021@layer base {
1022  :root {
1023    --background: 0 0% 100%;
1024    --foreground: 222.2 84% 4.9%;
1025    --primary: 222.2 47.4% 11.2%;
1026    --primary-foreground: 210 40% 98%;
1027    --secondary: 210 40% 96.1%;
1028    --secondary-foreground: 222.2 47.4% 11.2%;
1029    --muted: 210 40% 96.1%;
1030    --muted-foreground: 215.4 16.3% 46.9%;
1031    --accent: 210 40% 96.1%;
1032    --accent-foreground: 222.2 47.4% 11.2%;
1033    --destructive: 0 84.2% 60.2%;
1034    --destructive-foreground: 210 40% 98%;
1035    --border: 214.3 31.8% 91.4%;
1036    --input: 214.3 31.8% 91.4%;
1037    --ring: 222.2 84% 4.9%;
1038    --radius: 0.5rem;
1039  }
1040
1041  .dark {
1042    --background: 222.2 84% 4.9%;
1043    --foreground: 210 40% 98%;
1044    --primary: 210 40% 98%;
1045    --primary-foreground: 222.2 47.4% 11.2%;
1046    /* ... other dark mode variables */
1047  }
1048}
1049```
1050
1051### Customizing Components
1052
1053Since you own the code, customize directly:
1054
1055```tsx
1056// components/ui/button.tsx
1057import * as React from "react"
1058import { Slot } from "@radix-ui/react-slot"
1059import { cva, type VariantProps } from "class-variance-authority"
1060import { cn } from "@/lib/utils"
1061
1062const buttonVariants = cva(
1063  "inline-flex items-center justify-center rounded-md text-sm font-medium transition-colors",
1064  {
1065    variants: {
1066      variant: {
1067        default: "bg-primary text-primary-foreground hover:bg-primary/90",
1068        destructive: "bg-destructive text-destructive-foreground hover:bg-destructive/90",
1069        outline: "border border-input bg-background hover:bg-accent",
1070        // Add custom variant
1071        custom: "bg-gradient-to-r from-purple-500 to-pink-500 text-white",
1072      },
1073      size: {
1074        default: "h-10 px-4 py-2",
1075        sm: "h-9 rounded-md px-3",
1076        lg: "h-11 rounded-md px-8",
1077        // Add custom size
1078        xl: "h-14 rounded-md px-10 text-lg",
1079      },
1080    },
1081    defaultVariants: {
1082      variant: "default",
1083      size: "default",
1084    },
1085  }
1086)
1087
1088export interface ButtonProps
1089  extends React.ButtonHTMLAttributes<HTMLButtonElement>,
1090    VariantProps<typeof buttonVariants> {
1091  asChild?: boolean
1092}
1093
1094const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
1095  ({ className, variant, size, asChild = false, ...props }, ref) => {
1096    const Comp = asChild ? Slot : "button"
1097    return (
1098      <Comp
1099        className={cn(buttonVariants({ variant, size, className }))}
1100        ref={ref}
1101        {...props}
1102      />
1103    )
1104  }
1105)
1106Button.displayName = "Button"
1107
1108export { Button, buttonVariants }
1109```
1110
1111## Next.js Integration
1112
1113### App Router Setup
1114
1115For Next.js 13+ with App Router, ensure components use `"use client"` directive:
1116
1117```tsx
1118// src/components/ui/button.tsx
1119"use client"
1120
1121import * as React from "react"
1122import { Slot } from "@radix-ui/react-slot"
1123import { cva, type VariantProps } from "class-variance-authority"
1124import { cn } from "@/lib/utils"
1125
1126// ... rest of component
1127```
1128
1129### Layout Integration
1130
1131Add the Toaster to your root layout:
1132
1133```tsx
1134// app/layout.tsx
1135import { Toaster } from "@/components/ui/toaster"
1136import "./globals.css"
1137
1138export default function RootLayout({
1139  children,
1140}: {
1141  children: React.ReactNode
1142}) {
1143  return (
1144    <html lang="en" suppressHydrationWarning>
1145      <body className="min-h-screen bg-background font-sans antialiased">
1146        {children}
1147        <Toaster />
1148      </body>
1149    </html>
1150  )
1151}
1152```
1153
1154### Server Components
1155
1156When using shadcn/ui components in Server Components, wrap them in a Client Component:
1157
1158```tsx
1159// app/dashboard/page.tsx
1160import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
1161import { ButtonClient } from "@/components/ui/button-client"
1162
1163export default function DashboardPage() {
1164  return (
1165    <div className="container mx-auto p-6">
1166      <Card>
1167        <CardHeader>
1168          <CardTitle>Dashboard</CardTitle>
1169        </CardHeader>
1170        <CardContent>
1171          <ButtonClient>Interactive Button</ButtonClient>
1172        </CardContent>
1173      </Card>
1174    </div>
1175  )
1176}
1177```
1178
1179```tsx
1180// src/components/ui/button-client.tsx
1181"use client"
1182
1183import { Button } from "./button"
1184
1185export function ButtonClient(props: React.ComponentProps<typeof Button>) {
1186  return <Button {...props} />
1187}
1188```
1189
1190### Route Handlers with Forms
1191
1192Create API routes for form submissions:
1193
1194```tsx
1195// app/api/contact/route.ts
1196import { NextRequest, NextResponse } from "next/server"
1197import { z } from "zod"
1198
1199const contactSchema = z.object({
1200  name: z.string().min(2),
1201  email: z.string().email(),
1202  message: z.string().min(10),
1203})
1204
1205export async function POST(request: NextRequest) {
1206  try {
1207    const body = await request.json()
1208    const validated = contactSchema.parse(body)
1209
1210    // Process form data
1211    console.log("Form submission:", validated)
1212
1213    return NextResponse.json({ success: true })
1214  } catch (error) {
1215    if (error instanceof z.ZodError) {
1216      return NextResponse.json(
1217        { errors: error.errors },
1218        { status: 400 }
1219      )
1220    }
1221
1222    return NextResponse.json(
1223      { error: "Internal server error" },
1224      { status: 500 }
1225    )
1226  }
1227}
1228```
1229
1230### Form with Server Action
1231
1232Using Next.js 14+ Server Actions:
1233
1234```tsx
1235// app/contact/page.tsx
1236"use client"
1237
1238import { zodResolver } from "@hookform/resolvers/zod"
1239import { useForm } from "react-hook-form"
1240import * as z from "zod"
1241import { Button } from "@/components/ui/button"
1242import {
1243  Form,
1244  FormControl,
1245  FormField,
1246  FormItem,
1247  FormLabel,
1248  FormMessage,
1249} from "@/components/ui/form"
1250import { Input } from "@/components/ui/input"
1251import { Textarea } from "@/components/ui/textarea"
1252import { toast } from "@/components/ui/use-toast"
1253
1254const formSchema = z.object({
1255  name: z.string().min(2),
1256  email: z.string().email(),
1257  message: z.string().min(10),
1258})
1259
1260async function onSubmit(values: z.infer<typeof formSchema>) {
1261  try {
1262    const response = await fetch("/api/contact", {
1263      method: "POST",
1264      headers: { "Content-Type": "application/json" },
1265      body: JSON.stringify(values),
1266    })
1267
1268    if (!response.ok) throw new Error("Failed to submit")
1269
1270    toast({
1271      title: "Success!",
1272      description: "Your message has been sent.",
1273    })
1274  } catch (error) {
1275    toast({
1276      variant: "destructive",
1277      title: "Error",
1278      description: "Failed to send message. Please try again.",
1279    })
1280  }
1281}
1282
1283export default function ContactPage() {
1284  const form = useForm<z.infer<typeof formSchema>>({
1285    resolver: zodResolver(formSchema),
1286  })
1287
1288  return (
1289    <div className="container mx-auto max-w-2xl py-8">
1290      <Form {...form}>
1291        <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
1292          <FormField
1293            control={form.control}
1294            name="name"
1295            render={({ field }) => (
1296              <FormItem>
1297                <FormLabel>Name</FormLabel>
1298                <FormControl>
1299                  <Input placeholder="Your name" {...field} />
1300                </FormControl>
1301                <FormMessage />
1302              </FormItem>
1303            )}
1304          />
1305
1306          <FormField
1307            control={form.control}
1308            name="email"
1309            render={({ field }) => (
1310              <FormItem>
1311                <FormLabel>Email</FormLabel>
1312                <FormControl>
1313                  <Input type="email" placeholder="your@email.com" {...field} />
1314                </FormControl>
1315                <FormMessage />
1316              </FormItem>
1317            )}
1318          />
1319
1320          <FormField
1321            control={form.control}
1322            name="message"
1323            render={({ field }) => (
1324              <FormItem>
1325                <FormLabel>Message</FormLabel>
1326                <FormControl>
1327                  <Textarea
1328                    placeholder="Your message..."
1329                    className="resize-none"
1330                    {...field}
1331                  />
1332                </FormControl>
1333                <FormMessage />
1334              </FormItem>
1335            )}
1336          />
1337
1338          <Button type="submit" className="w-full">
1339            Send Message
1340          </Button>
1341        </form>
1342      </Form>
1343    </div>
1344  )
1345}
1346```
1347
1348### Metadata with shadcn/ui
1349
1350Using shadcn/ui components in metadata:
1351
1352```tsx
1353// app/layout.tsx
1354import { Metadata } from "next"
1355
1356export const metadata: Metadata = {
1357  title: {
1358    default: "My App",
1359    template: "%s | My App",
1360  },
1361  description: "Built with shadcn/ui and Next.js",
1362}
1363
1364// app/about/page.tsx
1365import { Metadata } from "next"
1366import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
1367
1368export const metadata: Metadata = {
1369  title: "About Us",
1370  description: "Learn more about our company",
1371}
1372
1373export default function AboutPage() {
1374  return (
1375    <div className="container mx-auto py-8">
1376      <Card>
1377        <CardHeader>
1378          <CardTitle>About Our Company</CardTitle>
1379        </CardHeader>
1380        <CardContent>
1381          <p>We build amazing products with modern web technologies.</p>
1382        </CardContent>
1383      </Card>
1384    </div>
1385  )
1386}
1387```
1388
1389### Font Optimization
1390
1391Optimize fonts with next/font:
1392
1393```tsx
1394// app/layout.tsx
1395import { Inter } from "next/font/google"
1396import { Toaster } from "@/components/ui/toaster"
1397import { cn } from "@/lib/utils"
1398import "./globals.css"
1399
1400const inter = Inter({ subsets: ["latin"] })
1401
1402export default function RootLayout({
1403  children,
1404}: {
1405  children: React.ReactNode
1406}) {
1407  return (
1408    <html lang="en" suppressHydrationWarning>
1409      <body className={cn("min-h-screen bg-background font-sans antialiased", inter.className)}>
1410        {children}
1411        <Toaster />
1412      </body>
1413    </html>
1414  )
1415}
1416```
1417
1418## Advanced Patterns
1419
1420### Form with Multiple Fields
1421
1422```tsx
1423const formSchema = z.object({
1424  username: z.string().min(2).max(50),
1425  email: z.string().email(),
1426  bio: z.string().max(160).min(4),
1427  role: z.enum(["admin", "user", "guest"]),
1428  notifications: z.boolean().default(false),
1429})
1430
1431export function AdvancedForm() {
1432  const form = useForm<z.infer<typeof formSchema>>({
1433    resolver: zodResolver(formSchema),
1434    defaultValues: {
1435      username: "",
1436      email: "",
1437      bio: "",
1438      role: "user",
1439      notifications: false,
1440    },
1441  })
1442
1443  function onSubmit(values: z.infer<typeof formSchema>) {
1444    console.log(values)
1445  }
1446
1447  return (
1448    <Form {...form}>
1449      <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-8">
1450        {/* Username field */}
1451        <FormField
1452          control={form.control}
1453          name="username"
1454          render={({ field }) => (
1455            <FormItem>
1456              <FormLabel>Username</FormLabel>
1457              <FormControl>
1458                <Input placeholder="johndoe" {...field} />
1459              </FormControl>
1460              <FormMessage />
1461            </FormItem>
1462          )}
1463        />
1464
1465        {/* Email field */}
1466        <FormField
1467          control={form.control}
1468          name="email"
1469          render={({ field }) => (
1470            <FormItem>
1471              <FormLabel>Email</FormLabel>
1472              <FormControl>
1473                <Input type="email" placeholder="john@example.com" {...field} />
1474              </FormControl>
1475              <FormMessage />
1476            </FormItem>
1477          )}
1478        />
1479
1480        {/* Textarea field */}
1481        <FormField
1482          control={form.control}
1483          name="bio"
1484          render={({ field }) => (
1485            <FormItem>
1486              <FormLabel>Bio</FormLabel>
1487              <FormControl>
1488                <Textarea
1489                  placeholder="Tell us about yourself"
1490                  className="resize-none"
1491                  {...field}
1492                />
1493              </FormControl>
1494              <FormMessage />
1495            </FormItem>
1496          )}
1497        />
1498
1499        {/* Select field */}
1500        <FormField
1501          control={form.control}
1502          name="role"
1503          render={({ field }) => (
1504            <FormItem>
1505              <FormLabel>Role</FormLabel>
1506              <Select onValueChange={field.onChange} defaultValue={field.value}>
1507                <FormControl>
1508                  <SelectTrigger>
1509                    <SelectValue placeholder="Select a role" />
1510                  </SelectTrigger>
1511                </FormControl>
1512                <SelectContent>
1513                  <SelectItem value="admin">Admin</SelectItem>
1514                  <SelectItem value="user">User</SelectItem>
1515                  <SelectItem value="guest">Guest</SelectItem>
1516                </SelectContent>
1517              </Select>
1518              <FormMessage />
1519            </FormItem>
1520          )}
1521        />
1522
1523        {/* Checkbox field */}
1524        <FormField
1525          control={form.control}
1526          name="notifications"
1527          render={({ field }) => (
1528            <FormItem className="flex flex-row items-start space-x-3 space-y-0">
1529              <FormControl>
1530                <Checkbox
1531                  checked={field.value}
1532                  onCheckedChange={field.onChange}
1533                />
1534              </FormControl>
1535              <div className="space-y-1 leading-none">
1536                <FormLabel>Email notifications</FormLabel>
1537                <FormDescription>
1538                  Receive emails about your account activity.
1539                </FormDescription>
1540              </div>
1541            </FormItem>
1542          )}
1543        />
1544
1545        <Button type="submit">Submit</Button>
1546      </form>
1547    </Form>
1548  )
1549}
1550```
1551
1552## Best Practices
1553
15541. **Accessibility**: Components use Radix UI primitives for ARIA compliance
15552. **Customization**: Modify components directly in your codebase
15563. **Type Safety**: Use TypeScript for type-safe props and state
15574. **Validation**: Use Zod schemas for form validation
15585. **Styling**: Leverage Tailwind utilities and CSS variables
15596. **Consistency**: Use the same component patterns across your app
15607. **Testing**: Components are testable with React Testing Library
15618. **Performance**: Components are optimized and tree-shakeable
1562
1563## Common Component Combinations
1564
1565### Login Form
1566
1567```tsx
1568<Card className="w-[350px]">
1569  <CardHeader>
1570    <CardTitle>Login</CardTitle>
1571    <CardDescription>Enter your credentials to continue</CardDescription>
1572  </CardHeader>
1573  <CardContent>
1574    <Form {...form}>
1575      <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
1576        <FormField
1577          control={form.control}
1578          name="email"
1579          render={({ field }) => (
1580            <FormItem>
1581              <FormLabel>Email</FormLabel>
1582              <FormControl>
1583                <Input type="email" placeholder="you@example.com" {...field} />
1584              </FormControl>
1585              <FormMessage />
1586            </FormItem>
1587          )}
1588        />
1589        <FormField
1590          control={form.control}
1591          name="password"
1592          render={({ field }) => (
1593            <FormItem>
1594              <FormLabel>Password</FormLabel>
1595              <FormControl>
1596                <Input type="password" {...field} />
1597              </FormControl>
1598              <FormMessage />
1599            </FormItem>
1600          )}
1601        />
1602        <Button type="submit" className="w-full">Login</Button>
1603      </form>
1604    </Form>
1605  </CardContent>
1606</Card>
1607```
1608
1609## References
1610
1611- Official Docs: https://ui.shadcn.com
1612- Radix UI: https://www.radix-ui.com
1613- React Hook Form: https://react-hook-form.com
1614- Zod: https://zod.dev
1615- Tailwind CSS: https://tailwindcss.com
1616- Examples: https://ui.shadcn.com/examples