본문으로 바로가기 본문 바로가기
WIKI 기술 지식 베이스

Composition

원문 보기 위키 갱신

컴포넌트 합성 패턴으로 유연한 UI를 구축해요.

출처: HeroUI Composition

본문

HeroUI는 합성 패턴을 사용해서 유연하고 커스터마이징 가능한 컴포넌트를 만들어요. 렌더링되는 요소를 바꾸고, 컴포넌트를 함께 합성하고, 마크업을 완전히 제어할 수 있어요.

프레임워크 비의존 스타일 (Framework-Agnostic Styles)

HeroUI의 변형 함수는 @heroui/styles 패키지에서 사용할 수 있으며, React와 독립적으로 사용할 수 있어요. 따라서 Vue, Svelte 및 기타 프레임워크에서도 HeroUI의 디자인 시스템을 사용할 수 있어요:

// Import directly from @heroui/styles (framework-agnostic)
import { buttonVariants } from '@heroui/styles';

// Or import from @heroui/react (re-exports the same functions)
import { buttonVariants } from '@heroui/react';

두 임포트 모두 동일하게 동작해요. React가 아닌 프레임워크를 구축하거나 React 의존성을 끌어오지 않으려면 @heroui/styles를 사용하세요.

다형성 스타일링 (Polymorphic Styling)

변형 함수나 BEM 클래스를 사용해서 어떤 요소에든 HeroUI 스타일을 적용하세요. 전체 타입 안전성과 함께 프레임워크 컴포넌트, 네이티브 HTML 요소, 커스텀 컴포넌트에 컴포넌트 스타일을 확장하세요.

예시: 링크를 버튼으로 스타일링하기

buttonVariants 를 사용해서 Link 컴포넌트에 버튼 스타일을 적용할 수 있어요:

import { buttonVariants } from '@heroui/styles';
import Link from 'next/link';

// Style a Next.js Link as a primary button
<Link
  className={buttonVariants({ variant: "primary" })}
  href="/about"
>
  About
</Link>

// Style a native anchor as a secondary button with custom size
<a
  className={buttonVariants({ variant: "secondary", size: "lg" })}
  href="https://example.com"
>
  External Link
</a>

BEM 클래스를 직접 사용하기:

import Link from 'next/link';

// Apply button styles directly using BEM classes
<Link className="button button--primary" href="/about">
  About
</Link>

복합 컴포넌트 사용하기

HeroUI의 Root 컴포넌트 대신 커스텀 루트 요소를 사용하면 자식 컴포넌트가 컨텍스트 슬롯에 접근할 수 없어요. 변형 함수나 BEM 클래스를 사용해서 자식 컴포넌트에 className을 수동으로 전달할 수 있어요:

import { Link } from '@heroui/react';
import { linkVariants } from '@heroui/styles';
import NextLink from 'next/link';

// With custom root - pass className manually
const slots = linkVariants();

<NextLink className={slots.base()} href="/about">
  About Page
  <Link.Icon className={slots.icon()} />
</NextLink>

<NextLink className="link" href="/about">
  About Page
  <Link.Icon className="link__icon" />
</NextLink>

이 접근 방식은 HeroUI의 변형 함수와 BEM 클래스를 어떤 요소에든 적용할 수 있기 때문에 동작해요. 프레임워크 컴포넌트, 네이티브 요소, 커스텀 컴포넌트를 HeroUI의 디자인 시스템으로 스타일링할 수 있는 완전한 유연성을 제공해요.

직접 클래스 적용 (Direct Class Application)

링크나 다른 요소를 스타일링하는 가장 간단한 방법은 HeroUI의 BEM 클래스를 직접 적용하는 거예요. 이 접근 방식은 간단하며 모든 프레임워크나 베니라 HTML에서 동작해요.

Next.js Link 사용:

import Link from 'next/link';

<Link className="button button--tertiary" href="/">
  Return Home
</Link>

네이티브 앵커 사용:

<a className="button button--primary" href="/dashboard">
  Go to Dashboard
</a>

사용 가능한 버튼 클래스:

  • .button — 기본 버튼 스타일
  • .button--primary, .button--secondary, .button--tertiary, .button--danger, .button--ghost — 변형
  • .button--sm, .button--md, .button--lg — 크기
  • .button--icon-only — 아이콘 전용 버튼

이 접근 방식은 HeroUI가 어떤 요소에도 적용할 수 있는 BEM 클래스를 사용하기 때문에 동작해요. 컴포넌트의 인터랙티브 기능(예: onPress 핸들러)이 필요 없고 시각적 스타일링만 원할 때 완벽해요.

변형 함수 사용하기 (Using Variant Functions)

더 많은 제어와 타입 안전성을 원한다면 변형 함수를 사용해서 HeroUI 스타일을 프레임워크별 컴포넌트나 커스텀 요소에 적용하세요. 변형 함수는 @heroui/styles(프레임워크 비의존)와 @heroui/react(재내보내기) 모두에서 사용할 수 있어요.

Next.js Link 사용:

import { Link } from '@heroui/react';
import { linkVariants } from '@heroui/styles';
import NextLink from 'next/link';

const slots = linkVariants();

<NextLink className={slots.base()} href="/about">
  About Page
  <Link.Icon className={slots.icon()} />
</NextLink>

Button 스타일 사용:

import { buttonVariants } from '@heroui/styles';
import Link from 'next/link';

<Link
  className={buttonVariants({ variant: "primary", size: "md" })}
  href="/dashboard"
>
  Dashboard
</Link>

사용 가능한 변형 함수: 각 컴포넌트는 @heroui/styles에서 자신의 변형 함수(buttonVariants, chipVariants, linkVariants, spinnerVariants 등)를 내보내요. 타입 안전성을 유지하면서 어떤 요소에든 HeroUI의 디자인 시스템을 적용하려면 이들을 사용하세요.

복합 컴포넌트 (Compound Components)

HeroUI 컴포넌트는 복합 컴포넌트로 만들어져 있어요 — 함께 동작하는 여러 부분을 내보내요. 세 가지 유연한 방식으로 사용하세요:

옵션 1: 복합 패턴 (권장) — .Root 접미사 없이 메인 컴포넌트를 직접 사용하세요:

import { Alert } from '@heroui/react';

<Alert>
  <Alert.Icon />
  <Alert.Content>
    <Alert.Title>Success</Alert.Title>
    <Alert.Description>Your changes have been saved.</Alert.Description>
  </Alert.Content>
  <Alert.Close />
</Alert>

옵션 2: .Root가 있는 복합 패턴 — 명시적인 명명을 원한다면 .Root 접미사를 사용하세요:

import { Alert } from '@heroui/react';

<Alert.Root>
  <Alert.Icon />
  <Alert.Content>
    <Alert.Title>Success</Alert.Title>
    <Alert.Description>Your changes have been saved.</Alert.Description>
  </Alert.Content>
  <Alert.Close />
</Alert.Root>

옵션 3: 명명된 내보내기 — 각 부분을 개별적으로 임포트하세요:

import {
  AlertRoot,
  AlertIcon,
  AlertContent,
  AlertTitle,
  AlertDescription,
  AlertClose
} from '@heroui/react';

<AlertRoot>
  <AlertIcon />
  <AlertContent>
    <AlertTitle>Success</AlertTitle>
    <AlertDescription>Your changes have been saved.</AlertDescription>
  </AlertContent>
  <AlertClose />
</AlertRoot>

혼합 문법: 같은 컴포넌트에서 복합 패턴과 명명된 내보내기를 섞을 수 있어요:

import { Alert, AlertTitle, AlertDescription } from '@heroui/react';

<Alert>
  <Alert.Icon />
  <Alert.Content>
    <AlertTitle>Success</AlertTitle>
    <AlertDescription>Your changes have been saved.</AlertDescription>
  </Alert.Content>
  <Alert.Close />
</Alert>

단순 컴포넌트: Button 같은 단순 컴포넌트도 같은 방식으로 동작해요 — .Root가 필요 없어요:

import { Button } from '@heroui/react';

// Recommended - no .Root needed
<Button>Click me</Button>

// Or with .Root
<Button.Root>Click me</Button.Root>

// Or named export
import { ButtonRoot } from '@heroui/react';
<ButtonRoot>Click me</ButtonRoot>

장점: 세 가지 패턴 모두 유연성, 커스터마이징, 제어, 일관성을 제공해요. 코드베이스에 맞는 패턴을 선택하세요.

변형 함수 혼합하기 (Mixing Variant Functions)

다른 컴포넌트의 변형 함수를 결합해서 독특한 스타일을 만들 수 있어요:

import { Link } from '@heroui/react';
import { linkVariants, buttonVariants } from '@heroui/styles';

// Link styled with button variants
const buttonStyles = buttonVariants({ variant: "tertiary", size: "md" });

<Link
  className={buttonStyles}
  href="https://heroui.com"
>
  HeroUI
</Link>

커스텀 컴포넌트 (Custom Components)

HeroUI 프리미티브를 합성해서 자신만의 컴포넌트를 만드세요:

import { Button, Tooltip } from '@heroui/react';
import { buttonVariants } from '@heroui/styles';

// Link button component using variant functions
function LinkButton({ href, children, variant = "primary", ...props }) {
  return (
    <a
      href={href}
      className={buttonVariants({ variant, ...props })}
      {...props}
    >
      {children}
    </a>
  );
}

// Icon button with tooltip
function IconButton({ icon, label, ...props }) {
  return (
    <Tooltip>
      <Tooltip.Trigger>
        <Button isIconOnly aria-label={label} {...props}>
          <Icon icon={icon} />
        </Button>
      </Tooltip.Trigger>
      <Tooltip.Content>{label}</Tooltip.Content>
    </Tooltip>
  );
}

커스텀 변형 (Custom Variants)

컴포넌트의 변형 함수를 확장해서 커스텀 변형을 만드세요:

import type { ButtonRootProps } from "@heroui/react";
import type { VariantProps } from "tailwind-variants";

import { Button } from "@heroui/react";
import { buttonVariants, tv } from "@heroui/styles";

const myButtonVariants = tv({
  extend: buttonVariants,
  base: "text-md text-shadow-lg font-semibold shadow-md data-[pending=true]:opacity-40",
  variants: {
    radius: {
      lg: "rounded-lg",
      md: "rounded-md",
      sm: "rounded-sm",
      full: "rounded-full",
    },
    size: {
      sm: "h-10 px-4",
      md: "h-11 px-6",
      lg: "h-12 px-8",
      xl: "h-13 px-10",
    },
    variant: {
      primary: "text-white dark:bg-white/10 dark:text-white dark:hover:bg-white/15",
    },
  },
  defaultVariants: {
    radius: "full",
    variant: "primary",
  },
});

type MyButtonVariants = VariantProps<typeof myButtonVariants>;
export type MyButtonProps = Omit<ButtonRootProps, "className"> &
  MyButtonVariants & { className?: string };

function CustomButton({ className, radius, variant, ...props }: MyButtonProps) {
  return <Button className={myButtonVariants({ className, radius, variant })} {...props} />;
}

export function CustomVariants() {
  return <CustomButton>Custom Button</CustomButton>;
}

타입 참조: 컴포넌트 타입을 다룰 때는 명명된 타입 임포트나 객체 스타일 문법을 사용하세요.

권장 — 명명된 타입 임포트:

import type { ButtonRootProps, AvatarRootProps } from "@heroui/react";

type MyButtonProps = ButtonRootProps;
type MyAvatarProps = AvatarRootProps;

대안 — 객체 스타일 문법:

import { Button, Avatar } from "@heroui/react";

type MyButtonProps = Button["RootProps"];
type MyAvatarProps = Avatar["RootProps"];

참고: 네임스페이스 문법 Button.RootProps는 더 이상 지원되지 않아요. 대신 Button["RootProps"] 또는 명명된 임포트를 사용하세요.

커스텀 DOM 요소 (Custom DOM Element)

다음 컴포넌트에서 render 프롭을 사용해서 기본 DOM 요소 대신 커스텀 컴포넌트를 렌더링하세요.

예를 들어 Motion 버튼을 렌더링하고 상태를 사용해서 애니메이션을 구동할 수 있어요.

import {Button} from '@heroui/react';
import {motion} from 'motion/react';

<Button
  render={(domProps, {isPressed}) => (
    <motion.button
      {...domProps}
      animate={{scale: isPressed ? 0.9 : 1}} />
  )}>
  Press me
</Button>

render 프롭은 클라이언트 사이드 라우터의 링크 컴포넌트를 렌더링하거나 기존의 표현형 컴포넌트를 재사용할 때도 유용해요.

import {Link} from '@heroui/react';
import NextLink from 'next/link';

<Link
  render={({ref, ...domProps}) => (
    <NextLink {...domProps} ref={ref as React.Ref<HTMLAnchorElement>} href="/privacy-policy" />
  )}
>
  Privacy Policy
</Link>

컴포넌트의 동작과 접근성을 깨지 않으려면 다음 규칙을 따르세요:

  • 항상 기대되는 요소 타입을 렌더링하세요 (예: <button>이 기대된다면 <a>를 렌더링하지 마세요). 불일치가 감지되면 개발 모드에서 경고가 표시돼요.
  • 단일 루트 DOM 요소만 렌더링하세요 (프래그먼트 금지).
  • 항상 제공된 프롭을 기본 DOM 요소에 전달하고, 필요에 따라 mergeProps를 사용해 자신의 프롭과 병합하세요.

프레임워크 통합 (Framework Integration)

Next.js 사용:

타입 안전한 스타일링을 위해 변형 함수를 사용하세요:

import { buttonVariants } from '@heroui/styles';
import Link from 'next/link';

<Link
  className={buttonVariants({ variant: "primary" })}
  href="/dashboard"
>
  Dashboard
</Link>

아니면 BEM 클래스를 직접 적용하세요 (가장 간단):

import Link from 'next/link';

<Link className="button button--primary" href="/dashboard">
  Dashboard
</Link>

React Router 사용:

변형 함수를 사용하세요:

import { buttonVariants } from '@heroui/styles';
import { Link } from 'react-router-dom';

<Link
  className={buttonVariants({ variant: "primary" })}
  to="/dashboard"
>
  Dashboard
</Link>

아니면 BEM 클래스를 직접 적용하세요 (가장 간단):

import { Link } from 'react-router-dom';

<Link className="button button--primary" to="/dashboard">
  Dashboard
</Link>

Vue, Svelte 또는 기타 프레임워크 사용:

@heroui/styles에는 React 의존성이 없으므로 어떤 프레임워크에서도 직접 사용할 수 있어요:

<script setup>
import { buttonVariants } from '@heroui/styles';

const primaryButton = buttonVariants({ variant: "primary" });
</script>

<template>
  <button :class="primaryButton">Click me</button>
</template>

다음 단계 (Next Steps)

더 알아보기 (Learn more)