아코디언

아코디언

아코디언은 세로로 쌓인 대화형 헤더 목록으로, 각 헤더를 클릭하면 해당하는 콘텐츠 영역이 펼쳐지는 컴포넌트예요. 여러 섹션을 한 화면에 담되 공간을 절약하고 싶을 때 아주 유용하죠. shadcn/ui의 아코디언은 Radix UI의 프리미티브 위에 만들어져 있어서 접근성과 동작이 이미 검증되어 있어요.

출처: 문서

본문

설치하기

init 명령으로 프로젝트를 초기화했다면, 다음 명령어로 아코디언 컴포넌트를 바로 추가할 수 있어요.

CLI Manual
npx shadcn@latest add accordion

다음 의존성을 설치해 주세요.

npm install @radix-ui/react-accordion

다음 코드를 프로젝트에 복사해서 붙여넣어 주세요.

import 경로를 프로젝트 설정에 맞게 바꿔 주세요.

tailwind.config.js를 업데이트해 주세요.

tailwind.config.js 파일에 다음 애니메이션을 추가해 주세요.

/** @type {import('tailwindcss').Config} */
module.exports = {
  theme: {
    extend: {
      keyframes: {
        "accordion-down": {
          from: { height: "0" },
          to: { height: "var(--radix-accordion-content-height)" },
        },
        "accordion-up": {
          from: { height: "var(--radix-accordion-content-height)" },
          to: { height: "0" },
        },
      },
      animation: {
        "accordion-down": "accordion-down 0.2s ease-out",
        "accordion-up": "accordion-up 0.2s ease-out",
      },
    },
  },
}

사용하기

먼저 다음처럼 아코디언 관련 컴포넌트들을 import 해 주세요.

import {
  Accordion,
  AccordionContent,
  AccordionItem,
  AccordionTrigger,
} from "@/components/ui/accordion"

type prop을 single로 주고 collapsible을 붙이면, 하나의 항목만 열리면서 다시 클릭하면 접히는 동작을 구현할 수 있어요.

<Accordion type="single" collapsible>
  <AccordionItem value="item-1">
    <AccordionTrigger>Is it accessible?</AccordionTrigger>
    <AccordionContent>
      Yes. It adheres to the WAI-ARIA design pattern.
    </AccordionContent>
  </AccordionItem>
</Accordion>

더 알아보기 (Learn more)