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

Toast

원문 보기 위키 갱신

Toast는 사용자에게 임시 알림과 메시지를 보여주는 컴포넌트예요. 자동으로 사라지며 배치 위치를 커스터마이징할 수 있어요.

출처: HeroUI Toast

본문

사용법 (Usage)

import { Toast, toast } from '@heroui/react';
{"name": "toast-default"}

구조 (Anatomy)

<Toast.Provider>
  <Toast>
    <Toast.Indicator />
    <Toast.Content>
      <Toast.Title />
      <Toast.Description />
    </Toast.Content>
    <Toast.ActionButton />
    <Toast.CloseButton />
  </Toast>
</Toast.Provider>

예시 (Examples)

변형 (Variants)

{"name": "toast-variants"}

배치 (Placements)

{"name": "toast-placements"}

확장된 스택 (Expanded Stack)

{"name": "toast-expanded"}

간단한 토스트 (Simple Toasts)

{"name": "toast-simple"}

커스텀 인디케이터 (Custom Indicators)

{"name": "toast-custom-indicator"}

커스텀 토스트 렌더링 (Custom Toast Rendering)

{"name": "toast-custom-toast"}

프로미스와 로딩 (Promise & Loading)

{"name": "toast-promise"}

콜백 (Callbacks)

{"name": "toast-callbacks"}

커스텀 큐 (Custom Queues)

{"name": "toast-custom-queue"}

설정 (Setup)

프로바이더를 앱의 최상단에 렌더링하세요.

import { Toast, Button, toast } from '@heroui/react';

function App() {
  return (
    <div>
      <Toast.Provider />
      <Button onPress={() => toast("Simple message")}>
        Show toast
      </Button>
    </div>
  );
}

커스터마이징 (Customization)

Tailwind CSS

{"name": "toast-custom-styles"}

Global CSS

Toast 컴포넌트 클래스를 커스터마이징하려면 @layer components 지시어를 사용할 수 있어요. 더 알아보기.

@layer components {
  .toast {
    @apply rounded-xl shadow-lg;
  }

  .toast__content {
    @apply gap-2;
  }
}

스타일링 참고 (Styling Reference)

HeroUI는 BEM 방법론을 따라 컴포넌트 변형과 상태를 재사용하고 쉽게 커스터마이징할 수 있게 해요.

CSS 클래스 (CSS Classes)

Toast 컴포넌트는 다음 CSS 클래스를 사용해요 (소스 스타일 보기):

기본 클래스 [!toc]

  • .toast - 기본 토스트 컨테이너
  • .toast-region - 토스트 영역 컨테이너
  • .toast__content - 제목과 설명을 감싸는 콘텐츠 래퍼
  • .toast__indicator - 아이콘/인디케이터 컨테이너
  • .toast__title - 토스트 제목 텍스트
  • .toast__description - 토스트 설명 텍스트
  • .toast__action - 액션 버튼 컨테이너
  • .toast__close-button - 닫기 버튼 컨테이너

변형 클래스 [!toc]

  • .toast--default - 기본 회색 변형
  • .toast--accent - 강조 파란색 변형
  • .toast--success - 성공 초록색 변형
  • .toast--warning - 경고 노랑/주황 변형
  • .toast--danger - 위험 빨간색 변형

상호작용 상태 (Interactive States)

컴포넌트는 다양한 상태를 지원해요:

  • 맨 앞 (Frontmost): [data-frontmost] - 가장 위에 보이는 토스트에 적용돼요
  • 인덱스 (Index): [data-index] - 스택에서의 토스트 위치에 따라 적용돼요
  • 배치 (Placement): [data-placement="*"] - 토스트 영역 배치에 따라 적용돼요
  • 진입 (Entering): [data-entering] - 새 토스트의 첫 페인트에 적용돼요
  • 퇴장 (Exiting): [data-exiting] - 닫히는 토스트가 퇴장 전환을 재생하는 동안 적용돼요
  • 확장 (Expanded): [data-expanded] - 스택이 확장되는 동안 모든 토스트에 적용돼요
  • 숨김 (Hidden): [data-hidden] - maxVisibleToasts를 초과한 토스트에 적용돼요

API 참고 (API Reference)

Toast.Provider

Prop Type Default Description
placement "top start" | "top" | "top end" | "bottom start" | "bottom" | "bottom end" "bottom" Placement of the toast region
gap number 12 The gap between toasts in pixels
isExpanded boolean false Force the stack into its expanded layout (does not pause timers)
maxVisibleToasts number 3 Maximum number of toasts to display at once
hotkey string[] ["altKey", "KeyT"] Hotkey that moves focus to the toast region and expands the stack. Modifiers match KeyboardEvent boolean properties (e.g. "altKey"), other keys match event.code (e.g. "KeyT"). Modifiers you leave out must be up, so Alt+T does not also fire on Ctrl+Alt+T. Pass [] to disable
scaleFactor number 0.05 Scale factor for stacked toasts (0-1)
width number | string 460 Width of the toast in pixels or CSS value
queue ToastQueue<T> - Custom toast queue instance
children ReactNode | ((props: {toast: QueuedToast<T>}) => ReactNode) - Custom render function or children
className string - Additional CSS classes

Toast

Prop Type Default Description
toast QueuedToast<T> - Toast data from queue (required)
variant "default" | "accent" | "success" | "warning" | "danger" "default" Visual variant of the toast
placement ToastVariants["placement"] - Placement (inherited from Provider)
scaleFactor number - Scale factor (inherited from Provider)
className string - Additional CSS classes
children ReactNode - Toast content (ToastContent, ToastIndicator, etc.)

Toast.Content

Prop Type Default Description
children ReactNode - Content (typically ToastTitle and ToastDescription)
className string - Additional CSS classes

Toast.Indicator

Prop Type Default Description
variant ToastVariants["variant"] - Variant for default icon
children ReactNode - Custom indicator icon (defaults to variant icon)
className string - Additional CSS classes

Toast.Title

Prop Type Default Description
children ReactNode - Title text
className string - Additional CSS classes

Toast.Description

Prop Type Default Description
children ReactNode - Description text
className string - Additional CSS classes

Toast.ActionButton

Prop Type Default Description
children ReactNode - Action button content
className string - Additional CSS classes
All Button props - - Accepts all Button component props

Toast.CloseButton

Prop Type Default Description
className string - Additional CSS classes
All CloseButton props - - Accepts all CloseButton component props

ToastQueue

ToastQueue는 <Toast.Provider>의 상태를 관리해요. 상태는 React 밖에 저장되므로 앱 어디에서든 토스트를 트리거할 수 있어요.

생성자 옵션 (Constructor Options)

Option Type Default Description
exitDuration number 300 How long a closing toast stays mounted for its exit animation (0 removes immediately)
maxVisibleToasts number 3 Maximum number of toasts to display at once (visual only)
wrapUpdate (fn: () => void) => void - Function to wrap state updates (e.g. document.startViewTransition); by default updates are applied directly and animated with CSS transitions

메서드 (Methods)

Method Parameters Returns Description
add (content: T, options?: ToastOptions) string Add a toast to the queue, returns toast key
update (key: string, content: T, options?: {timeout?: number; onClose?: () => void}) boolean Update a toast in place, preserving its stack position; timeout restarts the countdown (0 keeps it open), omit it to keep the current countdown. Returns false if the toast no longer exists
close (key: string) void Close a toast by its key
pauseAll () void Pause all toast timers
resumeAll () void Resume all toast timers
clear () void Close all toasts (each toast animates out and fires its onClose)
subscribe (fn: () => void) () => void Subscribe to queue changes, returns unsubscribe function

toast 함수 (toast Function)

기본 toast 함수는 토스트를 표시하는 편리한 메서드를 제공해요:

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

// Basic toast (auto-dismisses after 4 seconds by default)
toast("Event has been created");

// Variant methods (also auto-dismiss after 4 seconds by default)
toast.success("File saved");
toast.info("New update available");
toast.warning("Please check your settings");
toast.danger("Something went wrong");

// With options. The returned id lets the action close its own toast.
const eventId = toast("Event has been created", {
  description: "Your event has been scheduled for tomorrow",
  variant: "default",
  timeout: 5000, // Custom timeout: 5 seconds
  onClose: () => console.log("Closed"),
  actionProps: {
    children: "View",
    onPress: () => toast.close(eventId),
  },
  indicator: <CustomIcon />,
});

// Update an existing toast in place (keeps its position in the stack).
// Options you omit are inherited, so pass `timeout` to start a countdown
// on a toast that was created persistent.
const id = toast("Saving…", { timeout: 0 });
toast.update(id, "Saved", { variant: "success", timeout: 4000 });

// Promise support (automatically shows loading spinner). The loading toast
// updates in place when the promise settles — same toast, same stack
// position; the auto-dismiss countdown starts at that point.
toast.promise(
  uploadFile(),
  {
    loading: "Uploading file...",
    success: (data) => `File ${data.filename} uploaded`,
    error: "Failed to upload file",
  }
);

// Manual loading state (persistent toast - no auto-dismiss)
const loadingId = toast("Creating event...", {
  isLoading: true,
  timeout: 0, // Persistent toast that doesn't auto-dismiss
});

// Later, update in place and start the auto-dismiss countdown
toast.update(loadingId, "Event created", { variant: "success", timeout: 4000 });

// Queue methods
toast.close(key);
toast.clear();
toast.pauseAll();
toast.resumeAll();

toast 옵션 (toast Options)

Option Type Default Description
title ReactNode - Toast title (first parameter for variant methods)
description ReactNode - Optional description text
variant "default" | "accent" | "success" | "warning" | "danger" "default" Visual variant
indicator ReactNode - Custom indicator icon (null to hide)
actionProps ButtonProps - Props for action button
isLoading boolean false Show loading spinner instead of indicator
timeout number 4000 Auto-dismiss timeout in milliseconds. Defaults to 4000ms (4 seconds). Set to 0 for persistent toasts that don't auto-dismiss
onClose () => void - Called when the toast is dismissed, as its exit animation starts

toast.promise 옵션 (toast.promise Options)

Option Type Default Description
loading ReactNode - Message shown while promise is pending
success ReactNode | ((data: T) => ReactNode) - Message shown on success (can be function)
error ReactNode | ((error: Error) => ReactNode) - Message shown on error (can be function)

접근성 (Accessibility)

각 토스트는 WAI-ARIA alertdialog 패턴을 구현하고, 라벨이 지정된 landmark 영역 안에 그룹으로 배치돼요:

  • Landmark 영역: 토스트는 F6로 도달 가능한 라벨이 있는 landmark에 렌더링돼요. Alt + T는 포커스를 바로 그곳으로 이동시켜요. 핫키는 hotkey 프롭으로 설정할 수 있고 빈 배열을 전달하면 비활성화할 수 있으며, 영역 라벨은 aria-label로 덮어쓸 수 있어요
  • 키보드: Tab은 보이는 토스트의 컨트롤에 도달하고, Escape는 확장된 스택을 접으며, 포커스된 토스트를 닫으면 가장 가까운 남은 토스트로 포커스가 이동해요
  • 스크린 리더: 각 토스트는 제목과 설명이 연결된 role="alertdialog"를 사용해요. 새 토스트는 자동으로 알림돼요
  • 타이머: 스택을 호버하거나 포커스하는 동안, 그리고 페이지가 백그라운드 탭에 있는 동안 자동 닫김이 일시 중지돼요

더 알아보기 (Learn more)