ShadCN UI 패턴 - 2025년 11월 표준은(는) 무엇을 하나요?
사용 시기
- 새 UI 컴포넌트 구축 시
- 기존 컴포넌트를 ShadCN으로 리팩터링할 때
- 폼에 유효성 검사 구현 시
- 모달, 다이얼로그, 오버레이 생성 시
- 접근성 준수 확인 시
ShadCN UI를 사용하는 이유
- npm이 아닌 복사-붙여넣기 - 컴포넌트 코드의 완전한 소유권
- Radix UI 프리미티브 - 내장된 접근성(WCAG 2.1 AA 준수)
- TailwindCSS 우선 - 완전한 사용자 정의, CSS-in-JS 없음
- TypeScript 네이티브 - 타입 안전한 props 및 variants
- 서버 컴포넌트 호환 - Next.js 15 App Router와 함께 작동
핵심 원칙
1. 컴포넌트 설치 패턴
# 필요 시 개별 컴포넌트 설치
npx shadcn@latest add button
npx shadcn@latest add dialog
npx shadcn@latest add form
npx shadcn@latest add input
npx shadcn@latest add label
컴포넌트는 src/components/ui/ 디렉터리에 복사됩니다. 코드는 사용자가 소유합니다.
2. 컴포넌트 사용 패턴
Button 컴포넌트
import { Button } from "@/components/ui/button"
// ✅ DO: 시맨틱 variants 사용
<Button variant="default">저장</Button>
<Button variant="destructive">삭제</Button>
<Button variant="outline">취소</Button>
<Button variant="ghost">건너뛰기</Button>
<Button variant="link">더 알아보기</Button>
// ✅ DO: 크기 variants 사용
<Button size="default">중간</Button>
<Button size="sm">작게</Button>
<Button size="lg">크게</Button>
<Button size="icon"><Icon /></Button>
// ❌ DON'T: Button 컴포넌트 없이 사용자 정의 버튼 만들지 않음
<button className="px-4 py-2 bg-blue-500">나쁜 예</button>
Dialog/Modal 컴포넌트
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog"
// ✅ DO: 올바른 다이얼로그 구조 사용 (접근성)
<Dialog>
<DialogTrigger asChild>
<Button>설정 열기</Button>
</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle>설정</DialogTitle>
<DialogDescription>
여기서 애플리케이션 설정을 구성하세요.
</DialogDescription>
</DialogHeader>
{/* 다이얼로그 내용 */}
</DialogContent>
</Dialog>
// ❌ DON'T: DialogHeader 또는 DialogTitle 생략 (스크린 리더 중단)
<DialogContent>
<h2>설정</h2> {/* 잘못됨 - DialogTitle 사용 */}
</DialogContent>
Form 컴포넌트 (React Hook Form + Zod 사용)
import { useForm } from "react-hook-form"
import { zodResolver } from "@hookform/resolvers/zod"
import * as z from "zod"
import {
Form,
FormControl,
FormDescription,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@/components/ui/form"
import { Input } from "@/components/ui/input"
import { Button } from "@/components/ui/button"
// ✅ DO: 먼저 Zod 스키마 정의 (유효성 검사)
const formSchema = z.object({
email: z.string().email("유효하지 않은 이메일 주소"),
password: z.string().min(8, "비밀번호는 최소 8자 이상이어야 합니다"),
})
function LoginForm() {
const form = useForm<z.infer<typeof formSchema>>({
resolver: zodResolver(formSchema),
defaultValues: {
email: "",
password: "",
},
})
async function onSubmit(values: z.infer<typeof formSchema>) {
// 타입 안전하게 유효성 검사된 데이터
console.log(values)
}
return (
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
<FormField
control={form.control}
name="email"
render={({ field }) => (
<FormItem>
<FormLabel>이메일</FormLabel>
<FormControl>
<Input placeholder="[email protected]" {...field} />
</FormControl>
<FormDescription>
이메일을 공유하지 않습니다.
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="password"
render={({ field }) => (
<FormItem>
<FormLabel>비밀번호</FormLabel>
<FormControl>
<Input type="password" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<Button type="submit">로그인</Button>
</form>
</Form>
)
}
// ❌ DON'T: 유효성 검사 없이 비제어 폼 사용
<form>
<input name="email" /> {/* 유효성 검사 없음 */}
</form>
3. 서버 vs 클라이언트 컴포넌트
// ✅ DO: 정적 다이얼로그에는 서버 컴포넌트 사용
import { Dialog, DialogContent } from "@/components/ui/dialog"
export default function ServerDialog() {
// 'use client' 필요 없음
return <Dialog>...</Dialog>
}
// ✅ DO: 상태가 필요할 때는 클라이언트 컴포넌트 사용
'use client'
import { useState } from 'react'
import { Dialog, DialogContent } from "@/components/ui/dialog"
export function ClientDialog() {
const [open, setOpen] = useState(false)
return (
<Dialog open={open} onOpenChange={setOpen}>
<DialogContent>...</DialogContent>
</Dialog>
)
}
4. 접근성 요구사항
포커스 관리
// ✅ DO: 올바른 포커스를 위해 DialogTrigger를 asChild와 함께 사용
<DialogTrigger asChild>
<Button>열기</Button>
</DialogTrigger>
// ❌ DON'T: 적절한 포커스 처리 없이 수동으로 트리거
<Button onClick={() => setOpen(true)}>열기</Button>
키보드 내비게이션
// ✅ ShadCN이 자동으로 처리:
// - ESC는 다이얼로그를 닫음
// - Tab은 포커스 가능한 요소를 탐색
// - Enter/Space는 버튼 활성화
// - 화살표 키는 메뉴 탐색
// ❌ DON'T: 특별한 이유 없이 기본 키보드 동작 재정의
스크린 리더 지원
// ✅ DO: 항상 DialogTitle 포함 (ARIA에 필요)
<DialogHeader>
<DialogTitle>프로젝트 삭제</DialogTitle>
<DialogDescription>
이 작업은 되돌릴 수 없습니다.
</DialogDescription>
</DialogHeader>
// ❌ DON'T: 시각적으로 숨겨진 제목을 잘못 사용
<DialogTitle className="sr-only">삭제</DialogTitle>
// 명확한 시각적 대안이 있는 경우에만 숨김
5. 자주 사용하는 컴포넌트
| 컴포넌트 | 사용 사례 | 주요 Props |
|---|---|---|
Button | 모든 클릭 가능한 동작 | variant, size, asChild |
Dialog | 모달, 확인 | open, onOpenChange |
Sheet | 사이드 패널, 서랍 | side, open, onOpenChange |
Popover | 툴팁, 메뉴 | open, onOpenChange |
Form | 모든 폼 | form (useForm에서) |
Input | 텍스트 입력 | type, placeholder |
Select | 드롭다운 | value, onValueChange |
Checkbox | 부울 입력 | checked, onCheckedChange |
RadioGroup | 단일 선택 | value, onValueChange |
Table | 데이터 테이블 | table (TanStack Table에서) |
Card | 콘텐츠 컨테이너 | CardHeader, CardContent, CardFooter |
Toast | 알림 | title, description, variant |
Command | 명령 팔레트 | onSelect |
Tabs | 탭 내비게이션 | value, onValueChange |
6. TailwindCSS 모범 사례
// ✅ DO: Tailwind 유틸리티 클래스 사용
<Button className="w-full mt-4">제출</Button>
// ✅ DO: 조건부 클래스에 cn() 헬퍼 사용
import { cn } from "@/lib/utils"
<Button className={cn(
"w-full",
isLoading && "opacity-50 cursor-not-allowed"
)}>
제출
</Button>
// ❌ DON'T: 인라인 스타일 사용
<Button style={{ width: '100%', marginTop: '16px' }}>제출</Button>
// ❌ DON'T: 컴포넌트에 사용자 정의 CSS 파일 생성
// styles.css
.my-button { width: 100%; }
7. 다크 모드 지원
// ✅ DO: Tailwind 다크 모드 클래스 사용
<div className="bg-white dark:bg-gray-900 text-black dark:text-white">
콘텐츠
</div>
// ✅ ShadCN 컴포넌트는 다크 모드가 내장됨
<Button variant="default">
{/* 다크 모드에 자동으로 스타일 적용 */}
</Button>
잡아야 할 일반적인 실수
❌ DialogTitle 누락 (접근성 위반)
// 나쁜 예
<DialogContent>
<h2>설정</h2>
<p>내용</p>
</DialogContent>
// 좋은 예
<DialogContent>
<DialogHeader>
<DialogTitle>설정</DialogTitle>
</DialogHeader>
<p>내용</p>
</DialogContent>
❌ 폼에 Form 컴포넌트를 사용하지 않음
// 나쁜 예 - 유효성 검사 없음, 사용자 경험 나쁨
<form>
<input name="email" />
<button type="submit">제출</button>
</form>
// 좋은 예 - 유효성 검사, 오류 메시지, 접근성
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)}>
<FormField name="email" ... />
</form>
</Form>
❌ variants 대신 색상 하드코딩
// 나쁜 예
<Button className="bg-red-500 hover:bg-red-600">삭제</Button>
// 좋은 예
<Button variant="destructive">삭제</Button>
❌ 트리거에 asChild를 사용하지 않음
// 나쁜 예 - 불필요하게 중첩된 버튼 생성
<DialogTrigger>
<Button>열기</Button>
</DialogTrigger>
// 렌더링: <button><button>열기</button></button> (잘못된 HTML)
// 좋은 예 - props를 단일 버튼으로 병합
<DialogTrigger asChild>
<Button>열기</Button>
</DialogTrigger>
// 렌더링: <button>열기</button>
ShadCN 컴포넌트 테스트
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { Dialog, DialogTrigger, DialogContent } from '@/components/ui/dialog'
describe('Dialog', () => {
it('트리거 클릭 시 열려야 함', async () => {
const user = userEvent.setup()
render(
<Dialog>
<DialogTrigger asChild>
<button>열기</button>
</DialogTrigger>
<DialogContent>
<div>다이얼로그 내용</div>
</DialogContent>
</Dialog>
)
// 다이얼로그 내용이 처음에 보이지 않아야 함
expect(screen.queryByText('다이얼로그 내용')).not.toBeInTheDocument()
// 트리거 클릭
await user.click(screen.getByText('열기'))
// 다이얼로그 내용이 보여야 함
expect(screen.getByText('다이얼로그 내용')).toBeInTheDocument()
})
it('ESC 키로 닫혀야 함', async () => {
const user = userEvent.setup()
render(
<Dialog defaultOpen>
<DialogContent>다이얼로그 내용</DialogContent>
</Dialog>
)
expect(screen.getByText('다이얼로그 내용')).toBeInTheDocument()
await user.keyboard('{Escape}')
expect(screen.queryByText('다이얼로그 내용')).not.toBeInTheDocument()
})
})
리소스
- 공식 문서: https://ui.shadcn.com
- Radix UI: https://www.radix-ui.com
- 예제: https://ui.shadcn.com/examples
- 테마: https://ui.shadcn.com/themes
2025년 11월 참고 사항
ShadCN UI는 2025년 11월 기준 React 컴포넌트 라이브러리의 업계 표준입니다. 모든 새로운 Quetrex 애플리케이션은 일관성, 접근성, 유지보수성을 위해 ShadCN UI를 사용해야 합니다.