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

Toast

원문 보기 위키 갱신

고품질이면서 비스타일(unstyled)인 React 토스트 컴포넌트로, 알림(notification)을 생성해요. 토스트는 화면 구석에 잠시 나타났다 사라지는 알림 메시지예요. Provider가 모든 토스트를 하나의 viewport에 렌더링하고, 토스트 매니저를 통해 앱 어디에서든 큐에 담을 수 있어요.

출처: Base UI Toast

본문

Demo

Tailwind

이 예시는 Tailwind CSS를 사용해 컴포넌트를 구현하는 방법을 보여줄게요.

/* index.tsx */
'use client';
import * as React from 'react';
import { Toast } from '@base-ui/react/toast';

export default function ExampleToast() {
  return (
    <Toast.Provider>
      <ToastButton />
      <Toast.Portal>
        <Toast.Viewport className="fixed top-auto right-[1rem] bottom-[1rem] z-1 mx-auto w-[calc(100vw-2rem)] sm:right-[2rem] sm:bottom-[2rem] sm:w-[22.5rem]">
          <ToastList />
        </Toast.Viewport>
      </Toast.Portal>
    </Toast.Provider>
  );
}

function ToastButton() {
  const toastManager = Toast.useToastManager();
  const [count, setCount] = React.useState(0);

  function createToast() {
    setCount((prev) => prev + 1);
    toastManager.add({
      title: `Toast ${count + 1} created`,
      description: 'This is a toast notification.',
    });
  }

  return (
    <button
      type="button"
      className="flex h-8 items-center justify-center gap-2 rounded-none border border-neutral-950 bg-white px-3 py-0 font-[inherit] text-sm leading-none whitespace-nowrap font-normal text-neutral-950 select-none hover:bg-neutral-100 active:bg-neutral-200 dark:border-white dark:bg-neutral-950 dark:text-white dark:hover:bg-neutral-800 dark:active:bg-neutral-700 disabled:border-neutral-500 disabled:text-neutral-500 focus-visible:outline-2 focus-visible:-outline-offset-1 focus-visible:outline-neutral-950 dark:focus-visible:outline-white"
      onClick={createToast}
    >
      Create toast
    </button>
  );
}

function ToastList() {
  const { toasts } = Toast.useToastManager();
  return toasts.map((toast) => (
    <Toast.Root
      key={toast.id}
      toast={toast}
      className="[--gap:0.75rem] [--peek:0.75rem] [--scale:calc(max(0,1-(var(--toast-index)*0.1)))] [--shrink:calc(1-var(--scale))] [--height:var(--toast-frontmost-height,var(--toast-height))] [--offset-y:calc(var(--toast-offset-y)*-1+calc(var(--toast-index)*var(--gap)*-1)+var(--toast-swipe-movement-y))] absolute right-0 bottom-0 left-auto z-[calc(1000-var(--toast-index))] mr-0 w-full origin-bottom [transform:translateX(var(--toast-swipe-movement-x))_translateY(calc(var(--toast-swipe-movement-y)-(var(--toast-index)*var(--peek))-(var(--shrink)*var(--height))))_scale(var(--scale))] border border-neutral-950 bg-white text-neutral-950 shadow-[0.25rem_0.25rem_0] shadow-black/12 select-none dark:border-white dark:bg-neutral-950 dark:text-white dark:shadow-none after:absolute after:top-full after:left-0 after:h-[calc(var(--gap)+1px)] after:w-full after:content-[''] data-ending-style:opacity-0 data-expanded:[transform:translateX(var(--toast-swipe-movement-x))_translateY(calc(var(--offset-y)))] data-limited:opacity-0 data-starting-style:[transform:translateY(150%)] [&[data-ending-style]:not([data-limited]):not([data-swipe-direction])]:[transform:translateY(150%)] data-ending-style:data-[swipe-direction=down]:[transform:translateY(calc(var(--toast-swipe-movement-y)+150%))] data-expanded:data-ending-style:data-[swipe-direction=down]:[transform:translateY(calc(var(--toast-swipe-movement-y)+150%))] data-ending-style:data-[swipe-direction=left]:[transform:translateX(calc(var(--toast-swipe-movement-x)-150%))_translateY(var(--offset-y))] data-expanded:data-ending-style:data-[swipe-direction=left]:[transform:translateX(calc(var(--toast-swipe-movement-x)-150%))_translateY(var(--offset-y))] data-ending-style:data-[swipe-direction=right]:[transform:translateX(calc(var(--toast-swipe-movement-x)+150%))_translateY(var(--offset-y))] data-expanded:data-ending-style:data-[swipe-direction=right]:[transform:translateX(calc(var(--toast-swipe-movement-x)+150%))_translateY(var(--offset-y))] data-ending-style:data-[swipe-direction=up]:[transform:translateY(calc(var(--toast-swipe-movement-y)-150%))] data-expanded:data-ending-style:data-[swipe-direction=up]:[transform:translateY(calc(var(--toast-swipe-movement-y)-150%))] h-[var(--height)] data-expanded:h-[var(--toast-height)] [transition:transform_0.5s_cubic-bezier(0.22,1,0.36,1),opacity_0.5s,height_0.15s]"
    >
      <Toast.Content className="flex items-center gap-4 p-3 overflow-hidden transition-opacity duration-[250ms] ease-[cubic-bezier(0.22,1,0.36,1)] data-behind:opacity-0 data-expanded:opacity-100">
        <div className="flex min-w-0 flex-1 flex-col gap-1">
          <Toast.Title className="text-sm font-bold" />
          <Toast.Description className="text-sm" />
        </div>
        <Toast.Close className="flex h-8 shrink-0 items-center justify-center gap-2 rounded-none border border-neutral-950 bg-white px-3 py-0 font-[inherit] text-sm leading-none whitespace-nowrap font-normal text-neutral-950 hover:not-data-disabled:bg-neutral-100 active:not-data-disabled:bg-neutral-200 dark:border-white dark:bg-neutral-950 dark:text-white dark:hover:not-data-disabled:bg-neutral-800 dark:active:not-data-disabled:bg-neutral-700 data-disabled:border-neutral-500 data-disabled:text-neutral-500 disabled:border-neutral-500 disabled:text-neutral-500 dark:data-disabled:border-neutral-400 dark:data-disabled:text-neutral-400 focus-visible:outline-2 focus-visible:-outline-offset-1 focus-visible:outline-neutral-950 dark:focus-visible:outline-white">
          Dismiss
        </Toast.Close>
      </Toast.Content>
    </Toast.Root>
  ));
}

CSS Modules

이 예시는 CSS Modules를 사용해 컴포넌트를 구현하는 방법을 보여줄게요.

/* index.module.css */
.Viewport {
  position: fixed;
  z-index: 1;
  width: calc(100vw - 2rem);
  margin: 0 auto;
  bottom: 1rem;
  right: 1rem;
  left: auto;
  top: auto;

  @media (min-width: 500px) {
    bottom: 2rem;
    right: 2rem;
    width: 22.5rem;
  }
}

.Toast {
  --gap: 0.75rem;
  --peek: 0.75rem;
  --scale: calc(max(0, 1 - (var(--toast-index) * 0.1)));
  --shrink: calc(1 - var(--scale));
  --height: var(--toast-frontmost-height, var(--toast-height));
  --offset-y: calc(
    var(--toast-offset-y) * -1 + (var(--toast-index) * var(--gap) * -1) +
      var(--toast-swipe-movement-y)
  );
  position: absolute;
  right: 0;
  margin: 0 auto;
  box-sizing: border-box;
  width: 100%;
  border: 1px solid oklch(14.5% 0 0deg);
  background-color: white;
  color: oklch(14.5% 0 0deg);
  box-shadow: 0.25rem 0.25rem 0 rgb(0 0 0 / 12%);
  transform-origin: bottom center;
  bottom: 0;
  left: auto;
  margin-right: 0;
  -webkit-user-select: none;
  user-select: none;
  transition:
    transform 0.5s cubic-bezier(0.22, 1, 0.36, 1),
    opacity 0.5s,
    height 0.15s;
  cursor: default;
  z-index: calc(1000 - var(--toast-index));
  height: var(--height);
  transform: translateX(var(--toast-swipe-movement-x))
    translateY(
      calc(
        var(--toast-swipe-movement-y) - (var(--toast-index) * var(--peek)) -
          (var(--shrink) * var(--height))
      )
    )
    scale(var(--scale));

  @media (prefers-color-scheme: dark) {
    border: 1px solid white;
    background-color: oklch(14.5% 0 0deg);
    color: white;
    box-shadow: none;
  }

  &[data-expanded] {
    transform: translateX(var(--toast-swipe-movement-x)) translateY(var(--offset-y));
    height: var(--toast-height);
  }

  &[data-starting-style],
  &[data-ending-style] {
    transform: translateY(150%);
  }

  &[data-limited] {
    opacity: 0;
  }

  &[data-ending-style] {
    opacity: 0;

    &[data-swipe-direction='up'] {
      transform: translateY(calc(var(--toast-swipe-movement-y) - 150%));
    }
    &[data-swipe-direction='left'] {
      transform: translateX(calc(var(--toast-swipe-movement-x) - 150%)) translateY(var(--offset-y));
    }
    &[data-swipe-direction='right'] {
      transform: translateX(calc(var(--toast-swipe-movement-x) + 150%)) translateY(var(--offset-y));
    }
    &[data-swipe-direction='down'] {
      transform: translateY(calc(var(--toast-swipe-movement-y) + 150%));
    }
  }

  &::after {
    content: '';
    position: absolute;
    top: 100%;
    width: 100%;
    left: 0;
    height: calc(var(--gap) + 1px);
  }

  &:focus-visible {
    outline: 2px solid oklch(14.5% 0 0deg);
    outline-offset: -1px;

    @media (prefers-color-scheme: dark) {
      outline-color: white;
    }
  }
}

.Content {
  box-sizing: border-box;
  display: flex;
  align-items: center;
  gap: 1rem;
  padding: 0.75rem;
  overflow: hidden;
  transition: opacity 0.25s cubic-bezier(0.22, 1, 0.36, 1);

  &[data-behind] {
    opacity: 0;
  }

  &[data-expanded] {
    opacity: 1;
  }
}

.Text {
  display: flex;
  flex-direction: column;
  gap: 0.25rem;
  min-width: 0;
  flex: 1;
}

.Title {
  font-weight: 700;
  font-size: 0.875rem;
  line-height: 1.25rem;
  margin: 0;
}

.Description {
  font-size: 0.875rem;
  line-height: 1.25rem;
  margin: 0;
}

.Close {
  display: flex;
  flex-shrink: 0;
  align-items: center;
  justify-content: center;
  gap: 0.5rem;
  height: 2rem;
  padding: 0 0.75rem;
  border: 1px solid oklch(14.5% 0 0deg);
  border-radius: 0;
  background-color: white;
  color: oklch(14.5% 0 0deg);
  font-family: inherit;
  font-size: 0.875rem;
  font-weight: 400;
  line-height: 1;
  white-space: nowrap;

  @media (prefers-color-scheme: dark) {
    border: 1px solid white;
    background-color: oklch(14.5% 0 0deg);
    color: white;
  }

  @media (hover: hover) {
    &:hover:not([data-disabled]) {
      background-color: oklch(97% 0 0deg);

      @media (prefers-color-scheme: dark) {
        background-color: oklch(26.9% 0 0deg);
      }
    }
  }

  &:active:not([data-disabled]) {
    background-color: oklch(92.2% 0 0deg);

    @media (prefers-color-scheme: dark) {
      background-color: oklch(37.1% 0 0deg);
    }
  }

  &[data-disabled] {
    color: oklch(55.6% 0 0deg);
    border-color: oklch(55.6% 0 0deg);

    @media (prefers-color-scheme: dark) {
      color: oklch(70.8% 0 0deg);
      border-color: oklch(70.8% 0 0deg);
    }
  }

  &:focus-visible {
    outline: 2px solid oklch(14.5% 0 0deg);
    outline-offset: -1px;

    @media (prefers-color-scheme: dark) {
      outline-color: white;
    }
  }
}

.Button {
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0.5rem;
  height: 2rem;
  padding: 0 0.75rem;
  margin: 0;
  border: 1px solid oklch(14.5% 0 0deg);
  border-radius: 0;
  background-color: white;
  font-family: inherit;
  font-size: 0.875rem;
  font-weight: 400;
  line-height: 1;
  white-space: nowrap;
  color: oklch(14.5% 0 0deg);
  -webkit-user-select: none;
  user-select: none;

  @media (prefers-color-scheme: dark) {
    border: 1px solid white;
    background-color: oklch(14.5% 0 0deg);
    color: white;
  }

  @media (hover: hover) {
    &:hover {
      background-color: oklch(97% 0 0deg);

      @media (prefers-color-scheme: dark) {
        background-color: oklch(26.9% 0 0deg);
      }
    }
  }

  &:active {
    background-color: oklch(92.2% 0 0deg);

    @media (prefers-color-scheme: dark) {
      background-color: oklch(37.1% 0 0deg);
    }
  }

  &:focus-visible {
    outline: 2px solid oklch(14.5% 0 0deg);
    outline-offset: -1px;

    @media (prefers-color-scheme: dark) {
      outline-color: white;
    }
  }
}
/* index.tsx */
'use client';
import * as React from 'react';
import { Toast } from '@base-ui/react/toast';
import styles from './index.module.css';

export default function ExampleToast() {
  return (
    <Toast.Provider>
      <ToastButton />
      <Toast.Portal>
        <Toast.Viewport className={styles.Viewport}>
          <ToastList />
        </Toast.Viewport>
      </Toast.Portal>
    </Toast.Provider>
  );
}

function ToastButton() {
  const toastManager = Toast.useToastManager();
  const [count, setCount] = React.useState(0);

  function createToast() {
    setCount((prev) => prev + 1);
    toastManager.add({
      title: `Toast ${count + 1} created`,
      description: 'This is a toast notification.',
    });
  }

  return (
    <button type="button" className={styles.Button} onClick={createToast}>
      Create toast
    </button>
  );
}

function ToastList() {
  const { toasts } = Toast.useToastManager();
  return toasts.map((toast) => (
    <Toast.Root key={toast.id} toast={toast} className={styles.Toast}>
      <Toast.Content className={styles.Content}>
        <div className={styles.Text}>
          <Toast.Title className={styles.Title} />
          <Toast.Description className={styles.Description} />
        </div>
        <Toast.Close className={styles.Close}>Dismiss</Toast.Close>
      </Toast.Content>
    </Toast.Root>
  ));
}

Anatomy

컴포넌트를 import하고 각 부분을 조립해요:

import { Toast } from '@base-ui/react/toast';

<Toast.Provider>
  <Toast.Portal>
    <Toast.Viewport>
      {/* Stacked toasts */}
      <Toast.Root>
        <Toast.Content>
          <Toast.Title />
          <Toast.Description />
          <Toast.Action />
          <Toast.Close />
        </Toast.Content>
      </Toast.Root>

      {/* Anchored toasts */}
      <Toast.Positioner>
        <Toast.Root>
          <Toast.Arrow />
          <Toast.Content>
            <Toast.Title />
            <Toast.Description />
            <Toast.Action />
            <Toast.Close />
          </Toast.Content>
        </Toast.Root>
      </Toast.Positioner>
    </Toast.Viewport>
  </Toast.Portal>
</Toast.Provider>;

General usage

  • <Toast.Provider>를 앱 전체에 감싸면 모든 토스트가 같은 viewport에서 렌더링되도록 보장할 수 있어요.
  • F6를 누르면 사용자가 토스트 viewport landmark 영역으로 이동할 수 있고, keyboard focus. data-base-ui-swipe-ignore 속성을 토스트 내부의 요소에 직접 추가하면 그 요소에서 스와이프로 닫는 제스처를 막을 수 있어요. 상호작용 요소는 자동으로 막혀요.

Global manager

<Toast.Provider>에 toastManager prop을 전달하면 전역 토스트 매니저를 만들 수 있어요. 이렇게 하면 React 트리 밖의 함수 같은 앱 어디에서든 동일한 토스트 렌더러를 사용하면서 토스트를 큐에 넣을 수 있어요.

생성된 toastManager는 Toast.useToastManager() 훅과 동일한 add, close, update, promise 메서드를 제공해요. 이 훅과 달리 React 트리 밖에 있기 때문에 반응형 toasts 배열을 반환하지 않아요.

const toastManager = Toast.createToastManager();
<Toast.Provider toastManager={toastManager}>

Stacking and animations

--toast-index CSS 변수로 토스트의 쌓임 순서를 정할 수 있어요. 0번 인덱스의 토스트가 맨 앞에 나타나요.

.Toast {
  z-index: calc(1000 - var(--toast-index));
  transform: scale(calc(max(0, 1 - (var(--toast-index) * 0.1))));
}

--toast-offset-y CSS 변수는 변환 오프셋으로 절대 위치를 잡을 때 토스트의 세로 오프셋을 정하는 데 써요. 보통 토스트 viewport에 마우스를 올리거나 포커스가 있을 때 나타나는 data-expanded 속성과 함께 사용해요.

.Toast[data-expanded] {
  transform: translateY(var(--toast-offset-y));
}

스택이 접혀 있을 때 --toast-frontmost-height CSS 변수로 각 토스트의 높이를 맨 앞 토스트 높이에 맞출 수 있고, <Toast.Content>를 사용해 뒤에 있는 토스트의 콘텐츠를 숨겨요. data-behind 속성은 맨 앞 토스트 뒤에 있는 콘텐츠를 표시하며, viewport가 확장되면 콘텐츠가 다시 나타나도록 data-expanded 속성과 함께 사용해요:

.Toast {
  height: var(--toast-frontmost-height, var(--toast-height));
}

.ToastContent {
  transition: opacity 0.25s;
}

/* @highlight-text "data-behind" */
.ToastContent[data-behind] {
  opacity: 0;
}

/* @highlight-text "data-expanded" */
.ToastContent[data-expanded] {
  opacity: 1;
}

--toast-swipe-movement-x와 --toast-swipe-movement-y CSS 변수는 변환 오프셋을 추가하기 위해 토스트의 스와이프 이동을 정하는 데 사용해요.

.Toast {
  transform: scale(calc(max(0, 1 - (var(--toast-index) * 0.1))))
    translateX(var(--toast-swipe-movement-x)) /* @highlight-text "--toast-swipe-movement-x" */
    /* @highlight-text "--toast-swipe-movement-y" */
    translateY(calc(var(--toast-swipe-movement-y) + (var(--toast-index) * -20%)));
}

data-swipe-direction 속성은 닫을 때 변환 오프셋을 추가하기 위해 토스트의 스와이프 방향을 정하는 데 사용해요.

&[data-ending-style] {
  opacity: 0;

  /* @highlight-text "data-swipe-direction" */
  &[data-swipe-direction='up'] {
    transform: translateY(calc(var(--toast-swipe-movement-y) - 150%));
  }
  /* @highlight-text "data-swipe-direction" */
  &[data-swipe-direction='down'] {
    transform: translateY(calc(var(--toast-swipe-movement-y) + 150%));
  }
  /* Note: --offset-y is defined locally in these examples and derives from
   --toast-offset-y, --toast-index, and swipe movement values */
  /* @highlight-text "data-swipe-direction" */
  &[data-swipe-direction='left'] {
    transform: translateX(calc(var(--toast-swipe-movement-x) - 150%)) translateY(var(--offset-y));
  }
  /* @highlight-text "data-swipe-direction" */
  &[data-swipe-direction='right'] {
    transform: translateX(calc(var(--toast-swipe-movement-x) + 150%)) translateY(var(--offset-y));
  }
}

data-limited 속성은 토스트가 limit 옵션을 초과했음을 나타내요. limited 토스트는 HTML inert 속성이 붙은 채로 마운트된 상태로 남아, 토스트를 숨기거나 다르게 애니메이션하는 데 유용해요.

updateKey 속성은 토스트가 업데이트되거나 upsert될 때 증가해요. 이 값은 애니메이션 이름을 바꿔 시선을 끄는 스타일을 다시 재생하거나, 재마운트가 괜찮다면 React key에 포함해 사용할 수 있어요.

Examples

Anchored toasts

토스트를 추가할 때 <Toast.Positioner>와 positionerProps 옵션을 사용하면 토스트를 특정 요소에 고정할 수 있어요. 동작을 트리거한 버튼 근처에 나타나는 일시적인 "Copied" 토스트 같은 상황별 피드백을 보여줄 때 유용해요.

고정된 토스트는 쌓이는 토스트와 별도의 <Toast.Provider>에서 렌더링하는 것이 좋아요. 각각을 앱 전체에서 별도로 관리하도록 전역 토스트 매니저를 만들 수 있어요:

const anchoredToastManager = Toast.createToastManager();
const stackedToastManager = Toast.createToastManager();

function App() {
  return (
    <React.Fragment>
      <Toast.Provider toastManager={anchoredToastManager}>
        <AnchoredToasts />
      </Toast.Provider>
      <Toast.Provider toastManager={stackedToastManager}>
        <StackedToasts />
      </Toast.Provider>

      {/* App content */}
    </React.Fragment>
  );
}

function AnchoredToasts() {
  const { toasts } = Toast.useToastManager();
  return (
    <Toast.Portal>
      <Toast.Viewport>
        {toasts.map((toast) => (
          <Toast.Positioner key={toast.id} toast={toast}>
            <Toast.Root toast={toast}>{/* ... */}</Toast.Root>
          </Toast.Positioner>
        ))}
      </Toast.Viewport>
    </Toast.Portal>
  );
}

function StackedToasts() {
  const { toasts } = Toast.useToastManager();
  return (
    <Toast.Portal>
      <Toast.Viewport>
        {toasts.map((toast) => (
          <Toast.Root key={toast.id} toast={toast}>
            {/* ... */}
          </Toast.Root>
        ))}
      </Toast.Viewport>
    </Toast.Portal>
  );
}

Demo

Tailwind

이 예시는 Tailwind CSS를 사용해 컴포넌트를 구현하는 방법을 보여줄게요.

/* index.tsx */
'use client';
import * as React from 'react';
import { Toast } from '@base-ui/react/toast';
import { Button } from '@base-ui/react/button';
import { Tooltip } from '@base-ui/react/tooltip';

const stackedToastManager = Toast.createToastManager();
const anchoredToastManager = Toast.createToastManager();

export default function ExampleToast() {
  return (
    <Tooltip.Provider>
      <Toast.Provider toastManager={anchoredToastManager}>
        <AnchoredToasts />
      </Toast.Provider>
      <Toast.Provider toastManager={stackedToastManager}>
        <StackedToasts />
      </Toast.Provider>

      <div className="flex items-center gap-2">
        <CopyButton />
        <StackedToastButton />
      </div>
    </Tooltip.Provider>
  );
}

function StackedToastButton() {
  function createToast() {
    stackedToastManager.add({
      description: 'Copied',
    });
  }

  return (
    <button
      type="button"
      className="flex h-8 items-center justify-center gap-2 rounded-none border border-neutral-950 bg-white px-3 py-0 font-[inherit] text-sm leading-none whitespace-nowrap font-normal text-neutral-950 select-none hover:bg-neutral-100 active:bg-neutral-200 dark:border-white dark:bg-neutral-950 dark:text-white dark:hover:bg-neutral-800 dark:active:bg-neutral-700 disabled:border-neutral-500 disabled:text-neutral-500 focus-visible:outline-2 focus-visible:-outline-offset-1 focus-visible:outline-neutral-950 dark:focus-visible:outline-white"
      onClick={createToast}
    >
      Stacked toast
    </button>
  );
}

function CopyButton() {
  const [copied, setCopied] = React.useState(false);
  const buttonRef = React.useRef<HTMLButtonElement | null>(null);

  function handleCopy() {
    setCopied(true);

    anchoredToastManager.add({
      description: 'Copied',
      positionerProps: {
        anchor: buttonRef.current,
        sideOffset: 10,
      },
      timeout: 1500,
      onClose() {
        setCopied(false);
      },
    });
  }

  return (
    <Tooltip.Root disabled={copied}>
      <Tooltip.Trigger
        ref={buttonRef}
        closeOnClick={false}
        className="flex h-8 w-8 items-center justify-center rounded-none border border-neutral-950 bg-white text-neutral-950 select-none hover:not-data-disabled:bg-neutral-100 active:not-data-disabled:bg-neutral-200 dark:border-white dark:bg-neutral-950 dark:text-white dark:hover:not-data-disabled:bg-neutral-800 dark:active:not-data-disabled:bg-neutral-700 data-disabled:border-neutral-500 data-disabled:text-neutral-500 disabled:border-neutral-500 disabled:text-neutral-500 dark:data-disabled:border-neutral-400 dark:data-disabled:text-neutral-400 focus-visible:outline-2 focus-visible:-outline-offset-1 focus-visible:outline-neutral-950 dark:focus-visible:outline-white"
        onClick={handleCopy}
        aria-label="Copy to clipboard"
        render={<Button disabled={copied} focusableWhenDisabled />}
      >
        {copied ? <CheckIcon /> : <ClipboardIcon />}
      </Tooltip.Trigger>
      <Tooltip.Portal>
        <Tooltip.Positioner sideOffset={10}>
          <Tooltip.Popup className="relative flex flex-col border border-neutral-950 bg-white px-2 py-1 text-sm text-neutral-950 origin-[var(--transform-origin)] shadow-[0.25rem_0.25rem_0] shadow-black/12 transition-[scale,opacity] duration-100 ease-out data-ending-style:opacity-0 data-ending-style:scale-[0.98] data-instant:transition-none data-starting-style:opacity-0 data-starting-style:scale-[0.98] dark:border-white dark:bg-neutral-950 dark:text-white dark:shadow-none">
            <Tooltip.Arrow className="relative block w-3 h-1.5 overflow-clip data-[side=bottom]:top-[-6px] data-[side=left]:right-[-9px] data-[side=left]:rotate-90 data-[side=right]:left-[-9px] data-[side=right]:-rotate-90 data-[side=top]:bottom-[-6px] data-[side=top]:rotate-180 before:content-[''] before:absolute before:bottom-0 before:left-1/2 before:w-[calc(6px*sqrt(2))] before:h-[calc(6px*sqrt(2))] before:bg-white dark:before:bg-neutral-950 before:border before:border-neutral-950 dark:before:border-white before:[transform:translate(-50%,50%)_rotate(45deg)]" />
            Copy
          </Tooltip.Popup>
        </Tooltip.Positioner>
      </Tooltip.Portal>
    </Tooltip.Root>
  );
}

function AnchoredToasts() {
  const { toasts } = Toast.useToastManager();
  return (
    <Toast.Portal>
      <Toast.Viewport className="outline-0">
        {toasts.map((toast) => (
          <Toast.Positioner
            key={toast.id}
            toast={toast}
            className="z-[calc(1000-var(--toast-index))]"
          >
            <Toast.Root
              toast={toast}
              className="relative flex flex-col w-max border border-neutral-950 bg-white px-2 py-1 text-sm text-neutral-950 origin-[var(--transform-origin)] shadow-[0.25rem_0.25rem_0] shadow-black/12 transition-[scale,opacity] duration-100 ease-out data-ending-style:opacity-0 data-ending-style:scale-[0.98] data-instant:transition-none data-starting-style:opacity-0 data-starting-style:scale-[0.98] dark:border-white dark:bg-neutral-950 dark:text-white dark:shadow-none focus-visible:outline-2 focus-visible:-outline-offset-1 focus-visible:outline-neutral-950 dark:focus-visible:outline-white"
            >
              <Toast.Arrow className="relative block w-3 h-1.5 overflow-clip data-[side=bottom]:top-[-6px] data-[side=left]:right-[-9px] data-[side=left]:rotate-90 data-[side=right]:left-[-9px] data-[side=right]:-rotate-90 data-[side=top]:bottom-[-6px] data-[side=top]:rotate-180 before:content-[''] before:absolute before:bottom-0 before:left-1/2 before:w-[calc(6px*sqrt(2))] before:h-[calc(6px*sqrt(2))] before:bg-white dark:before:bg-neutral-950 before:border before:border-neutral-950 dark:before:border-white before:[transform:translate(-50%,50%)_rotate(45deg)]" />
              <Toast.Content>
                <Toast.Description />
              </Toast.Content>
            </Toast.Root>
          </Toast.Positioner>
        ))}
      </Toast.Viewport>
    </Toast.Portal>
  );
}

function StackedToasts() {
  const { toasts } = Toast.useToastManager();
  return (
    <Toast.Portal>
      <Toast.Viewport className="fixed top-auto right-[1rem] bottom-[1rem] z-1 mx-auto w-[calc(100vw-2rem)] sm:right-[2rem] sm:bottom-[2rem] sm:w-[22.5rem]">
        {toasts.map((toast) => (
          <Toast.Root
            key={toast.id}
            toast={toast}
            className="[--gap:0.75rem] [--peek:0.75rem] [--scale:calc(max(0,1-(var(--toast-index)*0.1)))] [--shrink:calc(1-var(--scale))] [--height:var(--toast-frontmost-height,var(--toast-height))] [--offset-y:calc(var(--toast-offset-y)*-1+calc(var(--toast-index)*var(--gap)*-1)+var(--toast-swipe-movement-y))] absolute right-0 bottom-0 left-auto z-[calc(1000-var(--toast-index))] mr-0 w-full origin-bottom [transform:translateX(var(--toast-swipe-movement-x))_translateY(calc(var(--toast-swipe-movement-y)-(var(--toast-index)*var(--peek))-(var(--shrink)*var(--height))))_scale(var(--scale))] border border-neutral-950 bg-white text-neutral-950 shadow-[0.25rem_0.25rem_0] shadow-black/12 select-none dark:border-white dark:bg-neutral-950 dark:text-white dark:shadow-none after:absolute after:top-full after:left-0 after:h-[calc(var(--gap)+1px)] after:w-full after:content-[''] data-ending-style:opacity-0 data-expanded:[transform:translateX(var(--toast-swipe-movement-x))_translateY(calc(var(--offset-y)))] data-limited:opacity-0 data-starting-style:[transform:translateY(150%)] [&[data-ending-style]:not([data-limited]):not([data-swipe-direction])]:[transform:translateY(150%)] data-ending-style:data-[swipe-direction=down]:[transform:translateY(calc(var(--toast-swipe-movement-y)+150%))] data-expanded:data-ending-style:data-[swipe-direction=down]:[transform:translateY(calc(var(--toast-swipe-movement-y)+150%))] data-ending-style:data-[swipe-direction=left]:[transform:translateX(calc(var(--toast-swipe-movement-x)-150%))_translateY(var(--offset-y))] data-expanded:data-ending-style:data-[swipe-direction=left]:[transform:translateX(calc(var(--toast-swipe-movement-x)-150%))_translateY(var(--offset-y))] data-ending-style:data-[swipe-direction=right]:[transform:translateX(calc(var(--toast-swipe-movement-x)+150%))_translateY(var(--offset-y))] data-expanded:data-ending-style:data-[swipe-direction=right]:[transform:translateX(calc(var(--toast-swipe-movement-x)+150%))_translateY(var(--offset-y))] data-ending-style:data-[swipe-direction=up]:[transform:translateY(calc(var(--toast-swipe-movement-y)-150%))] data-expanded:data-ending-style:data-[swipe-direction=up]:[transform:translateY(calc(var(--toast-swipe-movement-y)-150%))] h-[var(--height)] data-expanded:h-[var(--toast-height)] [transition:transform_0.5s_cubic-bezier(0.22,1,0.36,1),opacity_0.5s,height_0.15s]"
          >
            <Toast.Content className="flex items-center gap-4 p-3 overflow-hidden transition-opacity duration-[250ms] ease-[cubic-bezier(0.22,1,0.36,1)] data-behind:opacity-0 data-expanded:opacity-100">
              <div className="flex min-w-0 flex-1 flex-col gap-1">
                <Toast.Title className="text-sm font-bold" />
                <Toast.Description className="text-sm" />
              </div>
              <Toast.Close className="flex h-8 shrink-0 items-center justify-center gap-2 rounded-none border border-neutral-950 bg-white px-3 py-0 font-[inherit] text-sm leading-none whitespace-nowrap font-normal text-neutral-950 hover:not-data-disabled:bg-neutral-100 active:not-data-disabled:bg-neutral-200 dark:border-white dark:bg-neutral-950 dark:text-white dark:hover:not-data-disabled:bg-neutral-800 dark:active:not-data-disabled:bg-neutral-700 data-disabled:border-neutral-500 data-disabled:text-neutral-500 disabled:border-neutral-500 disabled:text-neutral-500 dark:data-disabled:border-neutral-400 dark:data-disabled:text-neutral-400 focus-visible:outline-2 focus-visible:-outline-offset-1 focus-visible:outline-neutral-950 dark:focus-visible:outline-white">
                Dismiss
              </Toast.Close>
            </Toast.Content>
          </Toast.Root>
        ))}
      </Toast.Viewport>
    </Toast.Portal>
  );
}

function ClipboardIcon(props: React.ComponentProps<'svg'>) {
  return (
    <svg
      width="16"
      height="16"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.5"
      {...props}
      style={{ display: 'block', ...props.style }}
    >
      <rect width="8" height="4" x="8" y="2" rx="1" ry="1" />
      <path d="M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2" />
    </svg>
  );
}

function CheckIcon(props: React.ComponentProps<'svg'>) {
  return (
    <svg
      width="16"
      height="16"
      viewBox="0 0 16 16"
      fill="none"
      stroke="currentColor"
      {...props}
      style={{ display: 'block', ...props.style }}
    >
      <path d="m2.5 8.5 4 4 7-9" />
    </svg>
  );
}

CSS Modules

이 예시는 CSS Modules를 사용해 컴포넌트를 구현하는 방법을 보여줄게요.

/* index.module.css */
.AnchoredViewport {
  outline: 0;
}

.AnchoredPositioner {
  z-index: calc(1000 - var(--toast-index));
}

.AnchoredToast {
  box-sizing: border-box;
  position: relative;
  font-size: 0.875rem;
  line-height: 1.25rem;
  display: flex;
  flex-direction: column;
  width: max-content;
  padding: 0.25rem 0.5rem;
  border: 1px solid oklch(14.5% 0 0deg);
  background-color: white;
  color: oklch(14.5% 0 0deg);
  box-shadow: 0.25rem 0.25rem 0 rgb(0 0 0 / 12%);
  transform-origin: var(--transform-origin);
  transition:
    scale 100ms ease-out,
    opacity 100ms ease-out;

  @media (prefers-color-scheme: dark) {
    border: 1px solid white;
    background-color: oklch(14.5% 0 0deg);
    color: white;
    box-shadow: none;
  }

  &[data-starting-style],
  &[data-ending-style] {
    opacity: 0;
    scale: 0.98;
  }

  &[data-instant] {
    transition: none;
  }

  &:focus-visible {
    outline: 2px solid oklch(14.5% 0 0deg);
    outline-offset: -1px;

    @media (prefers-color-scheme: dark) {
      outline-color: white;
    }
  }
}

.StackedViewport {
  position: fixed;
  z-index: 1;
  width: calc(100vw - 2rem);
  margin: 0 auto;
  bottom: 1rem;
  right: 1rem;
  left: auto;
  top: auto;

  @media (min-width: 500px) {
    bottom: 2rem;
    right: 2rem;
    width: 22.5rem;
  }
}

.StackedToast {
  --gap: 0.75rem;
  --peek: 0.75rem;
  --scale: calc(max(0, 1 - (var(--toast-index) * 0.1)));
  --shrink: calc(1 - var(--scale));
  --height: var(--toast-frontmost-height, var(--toast-height));
  --offset-y: calc(
    var(--toast-offset-y) * -1 + (var(--toast-index) * var(--gap) * -1) +
      var(--toast-swipe-movement-y)
  );
  position: absolute;
  right: 0;
  margin: 0 auto;
  box-sizing: border-box;
  width: 100%;
  border: 1px solid oklch(14.5% 0 0deg);
  background-color: white;
  color: oklch(14.5% 0 0deg);
  box-shadow: 0.25rem 0.25rem 0 rgb(0 0 0 / 12%);
  transform-origin: bottom center;
  bottom: 0;
  left: auto;
  margin-right: 0;
  -webkit-user-select: none;
  user-select: none;
  transition:
    transform 0.5s cubic-bezier(0.22, 1, 0.36, 1),
    opacity 0.5s,
    height 0.15s;
  cursor: default;
  z-index: calc(1000 - var(--toast-index));
  height: var(--height);
  transform: translateX(var(--toast-swipe-movement-x))
    translateY(
      calc(
        var(--toast-swipe-movement-y) - (var(--toast-index) * var(--peek)) -
          (var(--shrink) * var(--height))
      )
    )
    scale(var(--scale));

  @media (prefers-color-scheme: dark) {
    border: 1px solid white;
    background-color: oklch(14.5% 0 0deg);
    color: white;
    box-shadow: none;
  }

  &[data-expanded] {
    transform: translateX(var(--toast-swipe-movement-x)) translateY(var(--offset-y));
    height: var(--toast-height);
  }

  &[data-starting-style],
  &[data-ending-style] {
    transform: translateY(150%);
  }

  &[data-limited] {
    opacity: 0;
  }

  &[data-ending-style] {
    opacity: 0;

    &[data-swipe-direction='up'] {
      transform: translateY(calc(var(--toast-swipe-movement-y) - 150%));
    }
    &[data-swipe-direction='left'] {
      transform: translateX(calc(var(--toast-swipe-movement-x) - 150%)) translateY(var(--offset-y));
    }
    &[data-swipe-direction='right'] {
      transform: translateX(calc(var(--toast-swipe-movement-x) + 150%)) translateY(var(--offset-y));
    }
    &[data-swipe-direction='down'] {
      transform: translateY(calc(var(--toast-swipe-movement-y) + 150%));
    }
  }

  &::after {
    content: '';
    position: absolute;
    top: 100%;
    width: 100%;
    left: 0;
    height: calc(var(--gap) + 1px);
  }
}

.Content {
  box-sizing: border-box;
  display: flex;
  align-items: center;
  gap: 1rem;
  padding: 0.75rem;
  overflow: hidden;
  transition: opacity 0.25s cubic-bezier(0.22, 1, 0.36, 1);

  &[data-behind] {
    opacity: 0;
  }

  &[data-expanded] {
    opacity: 1;
  }
}

.Text {
  display: flex;
  flex-direction: column;
  gap: 0.25rem;
  min-width: 0;
  flex: 1;
}

.Title {
  font-weight: 700;
  font-size: 0.875rem;
  line-height: 1.25rem;
  margin: 0;
}

.Description {
  font-size: 0.875rem;
  line-height: 1.25rem;
  margin: 0;
}

.Close {
  display: flex;
  flex-shrink: 0;
  align-items: center;
  justify-content: center;
  gap: 0.5rem;
  height: 2rem;
  padding: 0 0.75rem;
  border: 1px solid oklch(14.5% 0 0deg);
  border-radius: 0;
  background-color: white;
  color: oklch(14.5% 0 0deg);
  font-family: inherit;
  font-size: 0.875rem;
  font-weight: 400;
  line-height: 1;
  white-space: nowrap;

  @media (prefers-color-scheme: dark) {
    border: 1px solid white;
    background-color: oklch(14.5% 0 0deg);
    color: white;
  }

  @media (hover: hover) {
    &:hover:not([data-disabled]) {
      background-color: oklch(97% 0 0deg);

      @media (prefers-color-scheme: dark) {
        background-color: oklch(26.9% 0 0deg);
      }
    }
  }

  &:active:not([data-disabled]) {
    background-color: oklch(92.2% 0 0deg);

    @media (prefers-color-scheme: dark) {
      background-color: oklch(37.1% 0 0deg);
    }
  }

  &[data-disabled] {
    color: oklch(55.6% 0 0deg);
    border-color: oklch(55.6% 0 0deg);

    @media (prefers-color-scheme: dark) {
      color: oklch(70.8% 0 0deg);
      border-color: oklch(70.8% 0 0deg);
    }
  }

  &:focus-visible {
    outline: 2px solid oklch(14.5% 0 0deg);
    outline-offset: -1px;

    @media (prefers-color-scheme: dark) {
      outline-color: white;
    }
  }
}

.Tooltip {
  box-sizing: border-box;
  position: relative;
  font-size: 0.875rem;
  line-height: 1.25rem;
  display: flex;
  flex-direction: column;
  padding: 0.25rem 0.5rem;
  border: 1px solid oklch(14.5% 0 0deg);
  background-color: white;
  color: oklch(14.5% 0 0deg);
  box-shadow: 0.25rem 0.25rem 0 rgb(0 0 0 / 12%);
  transform-origin: var(--transform-origin);
  transition:
    scale 100ms ease-out,
    opacity 100ms ease-out;

  @media (prefers-color-scheme: dark) {
    border: 1px solid white;
    background-color: oklch(14.5% 0 0deg);
    color: white;
    box-shadow: none;
  }

  &[data-starting-style],
  &[data-ending-style] {
    opacity: 0;
    scale: 0.98;
  }

  &[data-instant] {
    transition: none;
  }
}

.AnchoredDescription {
  margin: 0;
}

.Arrow {
  display: block;
  position: relative;
  width: 12px;
  height: 6px;
  overflow: clip;

  &[data-side='top'] {
    bottom: -6px;
    rotate: 180deg;
  }

  &[data-side='bottom'] {
    top: -6px;
    rotate: 0deg;
  }

  &[data-side='left'] {
    right: -9px;
    rotate: 90deg;
  }

  &[data-side='right'] {
    left: -9px;
    rotate: -90deg;
  }

  &::before {
    content: '';
    position: absolute;
    bottom: 0;
    left: 50%;
    box-sizing: border-box;
    width: calc(6px * sqrt(2));
    height: calc(6px * sqrt(2));
    border: 1px solid oklch(14.5% 0 0deg);
    background-color: white;
    transform: translate(-50%, 50%) rotate(45deg);

    @media (prefers-color-scheme: dark) {
      border: 1px solid white;
      background-color: oklch(14.5% 0 0deg);
    }
  }
}

.ButtonGroup {
  display: flex;
  gap: 0.5rem;
  align-items: center;
}

.Button {
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0.5rem;
  height: 2rem;
  padding: 0 0.75rem;
  margin: 0;
  border: 1px solid oklch(14.5% 0 0deg);
  border-radius: 0;
  background-color: white;
  font-family: inherit;
  font-size: 0.875rem;
  font-weight: 400;
  line-height: 1;
  white-space: nowrap;
  color: oklch(14.5% 0 0deg);
  -webkit-user-select: none;
  user-select: none;

  @media (prefers-color-scheme: dark) {
    border: 1px solid white;
    background-color: oklch(14.5% 0 0deg);
    color: white;
  }

  @media (hover: hover) {
    &:hover {
      background-color: oklch(97% 0 0deg);

      @media (prefers-color-scheme: dark) {
        background-color: oklch(26.9% 0 0deg);
      }
    }
  }

  &:active {
    background-color: oklch(92.2% 0 0deg);

    @media (prefers-color-scheme: dark) {
      background-color: oklch(37.1% 0 0deg);
    }
  }

  &:focus-visible {
    outline: 2px solid oklch(14.5% 0 0deg);
    outline-offset: -1px;

    @media (prefers-color-scheme: dark) {
      outline-color: white;
    }
  }
}

.CopyButton {
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 2rem;
  height: 2rem;
  padding: 0;
  margin: 0;
  border: 1px solid oklch(14.5% 0 0deg);
  border-radius: 0;
  background-color: white;
  font-family: inherit;
  color: oklch(14.5% 0 0deg);
  -webkit-user-select: none;
  user-select: none;

  @media (prefers-color-scheme: dark) {
    border: 1px solid white;
    background-color: oklch(14.5% 0 0deg);
    color: white;
  }

  @media (hover: hover) {
    &:hover:not([data-disabled]) {
      background-color: oklch(97% 0 0deg);

      @media (prefers-color-scheme: dark) {
        background-color: oklch(26.9% 0 0deg);
      }
    }
  }

  &:active:not([data-disabled]) {
    background-color: oklch(92.2% 0 0deg);

    @media (prefers-color-scheme: dark) {
      background-color: oklch(37.1% 0 0deg);
    }
  }

  &:focus-visible {
    outline: 2px solid oklch(14.5% 0 0deg);
    outline-offset: -1px;

    @media (prefers-color-scheme: dark) {
      outline-color: white;
    }
  }
}
/* index.tsx */
'use client';
import * as React from 'react';
import { Toast } from '@base-ui/react/toast';
import { Button } from '@base-ui/react/button';
import { Tooltip } from '@base-ui/react/tooltip';
import styles from './index.module.css';

const anchoredToastManager = Toast.createToastManager();
const stackedToastManager = Toast.createToastManager();

export default function ExampleToast() {
  return (
    <Tooltip.Provider>
      <Toast.Provider toastManager={anchoredToastManager}>
        <AnchoredToasts />
      </Toast.Provider>
      <Toast.Provider toastManager={stackedToastManager}>
        <StackedToasts />
      </Toast.Provider>

      <div className={styles.ButtonGroup}>
        <CopyButton />
        <StackedToastButton />
      </div>
    </Tooltip.Provider>
  );
}

function StackedToastButton() {
  function createToast() {
    stackedToastManager.add({
      description: 'Copied',
    });
  }

  return (
    <button type="button" className={styles.Button} onClick={createToast}>
      Stacked toast
    </button>
  );
}

function CopyButton() {
  const [copied, setCopied] = React.useState(false);
  const buttonRef = React.useRef<HTMLButtonElement | null>(null);

  function handleCopy() {
    setCopied(true);

    anchoredToastManager.add({
      description: 'Copied',
      positionerProps: {
        anchor: buttonRef.current,
        sideOffset: 10,
      },
      timeout: 1500,
      onClose() {
        setCopied(false);
      },
    });
  }

  return (
    <Tooltip.Root disabled={copied}>
      <Tooltip.Trigger
        ref={buttonRef}
        closeOnClick={false}
        className={styles.CopyButton}
        onClick={handleCopy}
        aria-label="Copy to clipboard"
        render={<Button disabled={copied} focusableWhenDisabled />}
      >
        {copied ? <CheckIcon /> : <ClipboardIcon />}
      </Tooltip.Trigger>
      <Tooltip.Portal>
        <Tooltip.Positioner sideOffset={10}>
          <Tooltip.Popup className={styles.Tooltip}>
            <Tooltip.Arrow className={styles.Arrow} />
            Copy
          </Tooltip.Popup>
        </Tooltip.Positioner>
      </Tooltip.Portal>
    </Tooltip.Root>
  );
}

function AnchoredToasts() {
  const { toasts } = Toast.useToastManager();
  return (
    <Toast.Portal>
      <Toast.Viewport className={styles.AnchoredViewport}>
        {toasts.map((toast) => (
          <Toast.Positioner key={toast.id} toast={toast} className={styles.AnchoredPositioner}>
            <Toast.Root toast={toast} className={styles.AnchoredToast}>
              <Toast.Arrow className={styles.Arrow} />
              <Toast.Content>
                <Toast.Description className={styles.AnchoredDescription} />
              </Toast.Content>
            </Toast.Root>
          </Toast.Positioner>
        ))}
      </Toast.Viewport>
    </Toast.Portal>
  );
}

function StackedToasts() {
  const { toasts } = Toast.useToastManager();
  return (
    <Toast.Portal>
      <Toast.Viewport className={styles.StackedViewport}>
        {toasts.map((toast) => (
          <Toast.Root key={toast.id} toast={toast} className={styles.StackedToast}>
            <Toast.Content className={styles.Content}>
              <div className={styles.Text}>
                <Toast.Title className={styles.Title} />
                <Toast.Description className={styles.Description} />
              </div>
              <Toast.Close className={styles.Close}>Dismiss</Toast.Close>
            </Toast.Content>
          </Toast.Root>
        ))}
      </Toast.Viewport>
    </Toast.Portal>
  );
}

function ClipboardIcon(props: React.ComponentProps<'svg'>) {
  return (
    <svg
      width="16"
      height="16"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.5"
      {...props}
      style={{ display: 'block', ...props.style }}
    >
      <rect width="8" height="4" x="8" y="2" rx="1" ry="1" />
      <path d="M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2" />
    </svg>
  );
}

function CheckIcon(props: React.ComponentProps<'svg'>) {
  return (
    <svg
      width="16"
      height="16"
      viewBox="0 0 16 16"
      fill="none"
      stroke="currentColor"
      {...props}
      style={{ display: 'block', ...props.style }}
    >
      <path d="m2.5 8.5 4 4 7-9" />
    </svg>
  );
}

Custom position

토스트의 위치는 여러분의 CSS로 제어해요. 토스트의 위치를 바꾸려면 .Viewport와 .Root 스타일을 수정하면 돼요. 더 일반적인 컴포넌트는 data-position 속성을 받아 각 변형마다 CSS가 처리하게 할 수도 있어요. 다음은 상단 중앙 위치를 보여줄게요:

Demo

Tailwind

이 예시는 Tailwind CSS를 사용해 컴포넌트를 구현하는 방법을 보여줄게요.

/* index.tsx */
'use client';
import * as React from 'react';
import { Toast } from '@base-ui/react/toast';

export default function ExampleToast() {
  return (
    <Toast.Provider>
      <ToastButton />
      <Toast.Portal>
        <Toast.Viewport className="fixed top-[1rem] right-0 bottom-auto left-0 z-1 mx-auto w-[calc(100vw-2rem)] max-w-[22.5rem]">
          <ToastList />
        </Toast.Viewport>
      </Toast.Portal>
    </Toast.Provider>
  );
}

function ToastButton() {
  const toastManager = Toast.useToastManager();
  const [count, setCount] = React.useState(0);

  function createToast() {
    setCount((prev) => prev + 1);
    toastManager.add({
      title: `Toast ${count + 1} created`,
      description: 'This is a toast notification.',
    });
  }

  return (
    <button
      type="button"
      className="flex h-8 items-center justify-center gap-2 rounded-none border border-neutral-950 bg-white px-3 py-0 font-[inherit] text-sm leading-none whitespace-nowrap font-normal text-neutral-950 select-none hover:bg-neutral-100 active:bg-neutral-200 dark:border-white dark:bg-neutral-950 dark:text-white dark:hover:bg-neutral-800 dark:active:bg-neutral-700 disabled:border-neutral-500 disabled:text-neutral-500 focus-visible:outline-2 focus-visible:-outline-offset-1 focus-visible:outline-neutral-950 dark:focus-visible:outline-white"
      onClick={createToast}
    >
      Create toast
    </button>
  );
}

function ToastList() {
  const { toasts } = Toast.useToastManager();
  return toasts.map((toast) => (
    <Toast.Root
      key={toast.id}
      toast={toast}
      swipeDirection="up"
      className="[--gap:0.75rem] [--peek:0.75rem] [--scale:calc(max(0,1-(var(--toast-index)*0.1)))] [--shrink:calc(1-var(--scale))] [--height:var(--toast-frontmost-height,var(--toast-height))] [--offset-y:calc(var(--toast-offset-y)+(var(--toast-index)*var(--gap))+var(--toast-swipe-movement-y))] absolute top-0 right-0 left-0 z-[calc(1000-var(--toast-index))] mx-auto w-full origin-top [transform:translateX(var(--toast-swipe-movement-x))_translateY(calc(var(--toast-swipe-movement-y)+(var(--toast-index)*var(--peek))+(var(--shrink)*var(--height))))_scale(var(--scale))] border border-neutral-950 bg-white text-neutral-950 shadow-[0.25rem_0.25rem_0] shadow-black/12 select-none dark:border-white dark:bg-neutral-950 dark:text-white dark:shadow-none after:absolute after:bottom-full after:left-0 after:h-[calc(var(--gap)+1px)] after:w-full after:content-[''] data-ending-style:opacity-0 data-expanded:[transform:translateX(var(--toast-swipe-movement-x))_translateY(calc(var(--offset-y)))] data-limited:opacity-0 data-starting-style:[transform:translateY(-150%)] [&[data-ending-style]:not([data-limited]):not([data-swipe-direction])]:[transform:translateY(-150%)] data-ending-style:data-[swipe-direction=down]:[transform:translateY(calc(var(--toast-swipe-movement-y)+150%))] data-expanded:data-ending-style:data-[swipe-direction=down]:[transform:translateY(calc(var(--toast-swipe-movement-y)+150%))] data-ending-style:data-[swipe-direction=left]:[transform:translateX(calc(var(--toast-swipe-movement-x)-150%))_translateY(var(--offset-y))] data-expanded:data-ending-style:data-[swipe-direction=left]:[transform:translateX(calc(var(--toast-swipe-movement-x)-150%))_translateY(var(--offset-y))] data-ending-style:data-[swipe-direction=right]:[transform:translateX(calc(var(--toast-swipe-movement-x)+150%))_translateY(var(--offset-y))] data-expanded:data-ending-style:data-[swipe-direction=right]:[transform:translateX(calc(var(--toast-swipe-movement-x)+150%))_translateY(var(--offset-y))] data-ending-style:data-[swipe-direction=up]:[transform:translateY(calc(var(--toast-swipe-movement-y)-150%))] data-expanded:data-ending-style:data-[swipe-direction=up]:[transform:translateY(calc(var(--toast-swipe-movement-y)-150%))] h-[var(--height)] data-expanded:h-[var(--toast-height)] [transition:transform_0.5s_cubic-bezier(0.22,1,0.36,1),opacity_0.5s,height_0.15s]"
    >
      <Toast.Content className="flex items-center gap-4 p-3 overflow-hidden transition-opacity duration-[250ms] ease-[cubic-bezier(0.22,1,0.36,1)] data-behind:opacity-0 data-expanded:opacity-100">
        <div className="flex min-w-0 flex-1 flex-col gap-1">
          <Toast.Title className="text-sm font-bold" />
          <Toast.Description className="text-sm" />
        </div>
        <Toast.Close className="flex h-8 shrink-0 items-center justify-center gap-2 rounded-none border border-neutral-950 bg-white px-3 py-0 font-[inherit] text-sm leading-none whitespace-nowrap font-normal text-neutral-950 hover:not-data-disabled:bg-neutral-100 active:not-data-disabled:bg-neutral-200 dark:border-white dark:bg-neutral-950 dark:text-white dark:hover:not-data-disabled:bg-neutral-800 dark:active:not-data-disabled:bg-neutral-700 data-disabled:border-neutral-500 data-disabled:text-neutral-500 disabled:border-neutral-500 disabled:text-neutral-500 dark:data-disabled:border-neutral-400 dark:data-disabled:text-neutral-400 focus-visible:outline-2 focus-visible:-outline-offset-1 focus-visible:outline-neutral-950 dark:focus-visible:outline-white">
          Dismiss
        </Toast.Close>
      </Toast.Content>
    </Toast.Root>
  ));
}

CSS Modules

이 예시는 CSS Modules를 사용해 컴포넌트를 구현하는 방법을 보여줄게요.

/* index.module.css */
.Viewport {
  position: fixed;
  z-index: 1;
  width: calc(100vw - 2rem);
  max-width: 22.5rem;
  margin: 0 auto;
  top: 1rem;
  right: 0;
  left: 0;
  bottom: auto;
}

.Toast {
  --gap: 0.75rem;
  --peek: 0.75rem;
  --scale: calc(max(0, 1 - (var(--toast-index) * 0.1)));
  --shrink: calc(1 - var(--scale));
  --height: var(--toast-frontmost-height, var(--toast-height));
  --offset-y: calc(
    var(--toast-offset-y) + (var(--toast-index) * var(--gap)) + var(--toast-swipe-movement-y)
  );
  position: absolute;
  margin: 0 auto;
  box-sizing: border-box;
  width: 100%;
  border: 1px solid oklch(14.5% 0 0deg);
  background-color: white;
  color: oklch(14.5% 0 0deg);
  box-shadow: 0.25rem 0.25rem 0 rgb(0 0 0 / 12%);
  transform-origin: top center;
  top: 0;
  left: 0;
  right: 0;
  margin-right: auto;
  margin-left: auto;
  -webkit-user-select: none;
  user-select: none;
  transition:
    transform 0.5s cubic-bezier(0.22, 1, 0.36, 1),
    opacity 0.5s,
    height 0.15s;
  cursor: default;
  z-index: calc(1000 - var(--toast-index));
  height: var(--height);
  transform: translateX(var(--toast-swipe-movement-x))
    translateY(
      calc(
        var(--toast-swipe-movement-y) + (var(--toast-index) * var(--peek)) +
          (var(--shrink) * var(--height))
      )
    )
    scale(var(--scale));

  @media (prefers-color-scheme: dark) {
    border: 1px solid white;
    background-color: oklch(14.5% 0 0deg);
    color: white;
    box-shadow: none;
  }

  &[data-expanded] {
    transform: translateX(var(--toast-swipe-movement-x)) translateY(var(--offset-y));
    height: var(--toast-height);
  }

  &[data-starting-style],
  &[data-ending-style] {
    transform: translateY(-150%);
  }

  &[data-limited] {
    opacity: 0;
  }

  &[data-ending-style] {
    opacity: 0;

    &[data-swipe-direction='up'] {
      transform: translateY(calc(var(--toast-swipe-movement-y) - 150%));
    }
    &[data-swipe-direction='left'] {
      transform: translateX(calc(var(--toast-swipe-movement-x) - 150%)) translateY(var(--offset-y));
    }
    &[data-swipe-direction='right'] {
      transform: translateX(calc(var(--toast-swipe-movement-x) + 150%)) translateY(var(--offset-y));
    }
    &[data-swipe-direction='down'] {
      transform: translateY(calc(var(--toast-swipe-movement-y) + 150%));
    }
  }

  &::after {
    content: '';
    position: absolute;
    width: 100%;
    bottom: 100%;
    left: 0;
    height: calc(var(--gap) + 1px);
  }

  &:focus-visible {
    outline: 2px solid oklch(14.5% 0 0deg);
    outline-offset: -1px;

    @media (prefers-color-scheme: dark) {
      outline-color: white;
    }
  }
}

.Content {
  box-sizing: border-box;
  display: flex;
  align-items: center;
  gap: 1rem;
  padding: 0.75rem;
  overflow: hidden;
  transition: opacity 0.25s cubic-bezier(0.22, 1, 0.36, 1);

  &[data-behind] {
    opacity: 0;
  }

  &[data-expanded] {
    opacity: 1;
  }
}

.Text {
  display: flex;
  flex-direction: column;
  gap: 0.25rem;
  min-width: 0;
  flex: 1;
}

.Title {
  font-weight: 700;
  font-size: 0.875rem;
  line-height: 1.25rem;
  margin: 0;
}

.Description {
  font-size: 0.875rem;
  line-height: 1.25rem;
  margin: 0;
}

.Close {
  display: flex;
  flex-shrink: 0;
  align-items: center;
  justify-content: center;
  gap: 0.5rem;
  height: 2rem;
  padding: 0 0.75rem;
  border: 1px solid oklch(14.5% 0 0deg);
  border-radius: 0;
  background-color: white;
  color: oklch(14.5% 0 0deg);
  font-family: inherit;
  font-size: 0.875rem;
  font-weight: 400;
  line-height: 1;
  white-space: nowrap;

  @media (prefers-color-scheme: dark) {
    border: 1px solid white;
    background-color: oklch(14.5% 0 0deg);
    color: white;
  }

  @media (hover: hover) {
    &:hover:not([data-disabled]) {
      background-color: oklch(97% 0 0deg);

      @media (prefers-color-scheme: dark) {
        background-color: oklch(26.9% 0 0deg);
      }
    }
  }

  &:active:not([data-disabled]) {
    background-color: oklch(92.2% 0 0deg);

    @media (prefers-color-scheme: dark) {
      background-color: oklch(37.1% 0 0deg);
    }
  }

  &[data-disabled] {
    color: oklch(55.6% 0 0deg);
    border-color: oklch(55.6% 0 0deg);

    @media (prefers-color-scheme: dark) {
      color: oklch(70.8% 0 0deg);
      border-color: oklch(70.8% 0 0deg);
    }
  }

  &:focus-visible {
    outline: 2px solid oklch(14.5% 0 0deg);
    outline-offset: -1px;

    @media (prefers-color-scheme: dark) {
      outline-color: white;
    }
  }
}

.Button {
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0.5rem;
  height: 2rem;
  padding: 0 0.75rem;
  margin: 0;
  border: 1px solid oklch(14.5% 0 0deg);
  border-radius: 0;
  background-color: white;
  font-family: inherit;
  font-size: 0.875rem;
  font-weight: 400;
  line-height: 1;
  white-space: nowrap;
  color: oklch(14.5% 0 0deg);
  -webkit-user-select: none;
  user-select: none;

  @media (prefers-color-scheme: dark) {
    border: 1px solid white;
    background-color: oklch(14.5% 0 0deg);
    color: white;
  }

  @media (hover: hover) {
    &:hover {
      background-color: oklch(97% 0 0deg);

      @media (prefers-color-scheme: dark) {
        background-color: oklch(26.9% 0 0deg);
      }
    }
  }

  &:active {
    background-color: oklch(92.2% 0 0deg);

    @media (prefers-color-scheme: dark) {
      background-color: oklch(37.1% 0 0deg);
    }
  }

  &:focus-visible {
    outline: 2px solid oklch(14.5% 0 0deg);
    outline-offset: -1px;

    @media (prefers-color-scheme: dark) {
      outline-color: white;
    }
  }
}
/* index.tsx */
'use client';
import * as React from 'react';
import { Toast } from '@base-ui/react/toast';
import styles from './index.module.css';

export default function ExampleToast() {
  return (
    <Toast.Provider>
      <ToastButton />
      <Toast.Portal>
        <Toast.Viewport className={styles.Viewport}>
          <ToastList />
        </Toast.Viewport>
      </Toast.Portal>
    </Toast.Provider>
  );
}

function ToastButton() {
  const toastManager = Toast.useToastManager();
  const [count, setCount] = React.useState(0);

  function createToast() {
    setCount((prev) => prev + 1);
    toastManager.add({
      title: `Toast ${count + 1} created`,
      description: 'This is a toast notification.',
    });
  }

  return (
    <button type="button" className={styles.Button} onClick={createToast}>
      Create toast
    </button>
  );
}

function ToastList() {
  const { toasts } = Toast.useToastManager();
  return toasts.map((toast) => (
    <Toast.Root key={toast.id} toast={toast} swipeDirection="up" className={styles.Toast}>
      <Toast.Content className={styles.Content}>
        <div className={styles.Text}>
          <Toast.Title className={styles.Title} />
          <Toast.Description className={styles.Description} />
        </div>
        <Toast.Close className={styles.Close}>Dismiss</Toast.Close>
      </Toast.Content>
    </Toast.Root>
  ));
}

Undo action

토스트를 추가할 때 actionProps 옵션으로 내부의 액션 버튼용 props를 정의할 수 있어요. 이를 통해 토스트와 연결된 동작을 실행 취소할 수 있죠.

Demo

CSS Modules

이 예시는 CSS Modules를 사용해 컴포넌트를 구현하는 방법을 보여줄게요.

/* index.module.css */
.Viewport {
  position: fixed;
  z-index: 1;
  width: calc(100vw - 2rem);
  margin: 0 auto;
  bottom: 1rem;
  right: 1rem;
  left: auto;
  top: auto;

  @media (min-width: 500px) {
    bottom: 2rem;
    right: 2rem;
    width: 22.5rem;
  }
}

.Toast {
  --gap: 0.75rem;
  --peek: 0.75rem;
  --scale: calc(max(0, 1 - (var(--toast-index) * 0.1)));
  --shrink: calc(1 - var(--scale));
  --height: var(--toast-frontmost-height, var(--toast-height));
  --offset-y: calc(
    var(--toast-offset-y) * -1 + (var(--toast-index) * var(--gap) * -1) +
      var(--toast-swipe-movement-y)
  );
  position: absolute;
  right: 0;
  margin: 0 auto;
  box-sizing: border-box;
  width: 100%;
  border: 1px solid oklch(14.5% 0 0deg);
  background-color: white;
  color: oklch(14.5% 0 0deg);
  box-shadow: 0.25rem 0.25rem 0 rgb(0 0 0 / 12%);
  transform-origin: bottom center;
  bottom: 0;
  left: auto;
  margin-right: 0;
  -webkit-user-select: none;
  user-select: none;
  transition:
    transform 0.5s cubic-bezier(0.22, 1, 0.36, 1),
    opacity 0.5s,
    height 0.15s;
  cursor: default;
  z-index: calc(1000 - var(--toast-index));
  height: var(--height);
  transform: translateX(var(--toast-swipe-movement-x))
    translateY(
      calc(
        var(--toast-swipe-movement-y) - (var(--toast-index) * var(--peek)) -
          (var(--shrink) * var(--height))
      )
    )
    scale(var(--scale));

  @media (prefers-color-scheme: dark) {
    border: 1px solid white;
    background-color: oklch(14.5% 0 0deg);
    color: white;
    box-shadow: none;
  }

  &[data-expanded] {
    transform: translateX(var(--toast-swipe-movement-x)) translateY(var(--offset-y));
    height: var(--toast-height);
  }

  &[data-starting-style],
  &[data-ending-style] {
    transform: translateY(150%);
  }

  &[data-limited] {
    opacity: 0;
  }

  &[data-ending-style] {
    opacity: 0;

    &[data-swipe-direction='up'] {
      transform: translateY(calc(var(--toast-swipe-movement-y) - 150%));
    }
    &[data-swipe-direction='left'] {
      transform: translateX(calc(var(--toast-swipe-movement-x) - 150%)) translateY(var(--offset-y));
    }
    &[data-swipe-direction='right'] {
      transform: translateX(calc(var(--toast-swipe-movement-x) + 150%)) translateY(var(--offset-y));
    }
    &[data-swipe-direction='down'] {
      transform: translateY(calc(var(--toast-swipe-movement-y) + 150%));
    }
  }

  &::after {
    content: '';
    position: absolute;
    width: 100%;
    top: 100%;
    left: 0;
    height: calc(var(--gap) + 1px);
  }

  &:focus-visible {
    outline: 2px solid oklch(14.5% 0 0deg);
    outline-offset: -1px;

    @media (prefers-color-scheme: dark) {
      outline-color: white;
    }
  }
}

.Content {
  box-sizing: border-box;
  display: flex;
  align-items: center;
  gap: 1rem;
  padding: 0.75rem;
  overflow: hidden;
  transition: opacity 0.25s cubic-bezier(0.22, 1, 0.36, 1);

  &[data-behind] {
    opacity: 0;
  }

  &[data-expanded] {
    opacity: 1;
  }
}

.Text {
  display: flex;
  min-width: 0;
  flex: 1;
  flex-direction: column;
  align-items: start;
  gap: 0.75rem;
}

.Message {
  display: flex;
  flex-direction: column;
  gap: 0.25rem;
}

.Title {
  font-weight: 700;
  font-size: 0.875rem;
  line-height: 1.25rem;
  margin: 0;
}

.Description {
  font-size: 0.875rem;
  line-height: 1.25rem;
  margin: 0;
}

.UndoButton {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 0.5rem;
  height: 2rem;
  padding: 0 0.75rem;
  border: 1px solid oklch(14.5% 0 0deg);
  border-radius: 0;
  background-color: white;
  color: oklch(14.5% 0 0deg);
  font-family: inherit;
  font-size: 0.875rem;
  font-weight: 400;
  line-height: 1;
  white-space: nowrap;

  @media (prefers-color-scheme: dark) {
    border: 1px solid white;
    background-color: oklch(14.5% 0 0deg);
    color: white;
  }

  @media (hover: hover) {
    &:hover:not([data-disabled]) {
      background-color: oklch(97% 0 0deg);

      @media (prefers-color-scheme: dark) {
        background-color: oklch(26.9% 0 0deg);
      }
    }
  }

  &:active:not([data-disabled]) {
    background-color: oklch(92.2% 0 0deg);

    @media (prefers-color-scheme: dark) {
      background-color: oklch(37.1% 0 0deg);
    }
  }

  &[data-disabled] {
    color: oklch(55.6% 0 0deg);
    border-color: oklch(55.6% 0 0deg);

    @media (prefers-color-scheme: dark) {
      color: oklch(70.8% 0 0deg);
      border-color: oklch(70.8% 0 0deg);
    }
  }

  &:focus-visible {
    outline: 2px solid oklch(14.5% 0 0deg);
    outline-offset: -1px;

    @media (prefers-color-scheme: dark) {
      outline-color: white;
    }
  }
}

.Button {
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0.5rem;
  height: 2rem;
  padding: 0 0.75rem;
  margin: 0;
  border: 1px solid oklch(14.5% 0 0deg);
  border-radius: 0;
  background-color: white;
  font-family: inherit;
  font-size: 0.875rem;
  font-weight: 400;
  line-height: 1;
  white-space: nowrap;
  color: oklch(14.5% 0 0deg);
  -webkit-user-select: none;
  user-select: none;

  @media (prefers-color-scheme: dark) {
    border: 1px solid white;
    background-color: oklch(14.5% 0 0deg);
    color: white;
  }

  @media (hover: hover) {
    &:hover {
      background-color: oklch(97% 0 0deg);

      @media (prefers-color-scheme: dark) {
        background-color: oklch(26.9% 0 0deg);
      }
    }
  }

  &:active {
    background-color: oklch(92.2% 0 0deg);

    @media (prefers-color-scheme: dark) {
      background-color: oklch(37.1% 0 0deg);
    }
  }

  &:focus-visible {
    outline: 2px solid oklch(14.5% 0 0deg);
    outline-offset: -1px;

    @media (prefers-color-scheme: dark) {
      outline-color: white;
    }
  }
}
/* index.tsx */
'use client';
import * as React from 'react';
import { Toast } from '@base-ui/react/toast';
import styles from './index.module.css';

export default function UndoToastExample() {
  return (
    <Toast.Provider>
      <Form />
      <Toast.Portal>
        <Toast.Viewport className={styles.Viewport}>
          <ToastList />
        </Toast.Viewport>
      </Toast.Portal>
    </Toast.Provider>
  );
}

function Form() {
  const toastManager = Toast.useToastManager();

  function action() {
    const id = toastManager.add({
      title: 'Action performed',
      description: 'You can undo this action.',
      type: 'success',
      timeout: 10000,
      actionProps: {
        children: 'Undo',
        onClick() {
          toastManager.close(id);
          toastManager.add({
            title: 'Action undone',
          });
        },
      },
    });
  }

  return (
    <button type="button" onClick={action} className={styles.Button}>
      Perform action
    </button>
  );
}

function ToastList() {
  const { toasts } = Toast.useToastManager();
  return toasts.map((toast) => (
    <Toast.Root key={toast.id} toast={toast} className={styles.Toast}>
      <Toast.Content className={styles.Content}>
        <div className={styles.Text}>
          <div className={styles.Message}>
            <Toast.Title className={styles.Title} />
            <Toast.Description className={styles.Description} />
          </div>
          <Toast.Action className={styles.UndoButton} />
        </div>
      </Toast.Content>
    </Toast.Root>
  ));
}

Promise

비동기 토스트는 loading, success, error의 세 가지 상태로 만들 수 있어요. type 문자열이 이 상태들과 일치해 스타일을 바꿔요. 각 상태는 더 세밀한 제어를 위해 method options 객체도 받아요.

Demo

CSS Modules

이 예시는 CSS Modules를 사용해 컴포넌트를 구현하는 방법을 보여줄게요.

/* index.module.css */
.Viewport {
  position: fixed;
  z-index: 1;
  width: calc(100vw - 2rem);
  margin: 0 auto;
  bottom: 1rem;
  right: 1rem;
  left: auto;
  top: auto;

  @media (min-width: 500px) {
    bottom: 2rem;
    right: 2rem;
    width: 22.5rem;
  }
}

.Toast {
  --gap: 0.75rem;
  --peek: 0.75rem;
  --scale: calc(max(0, 1 - (var(--toast-index) * 0.1)));
  --shrink: calc(1 - var(--scale));
  --height: var(--toast-frontmost-height, var(--toast-height));
  --offset-y: calc(
    var(--toast-offset-y) * -1 + (var(--toast-index) * var(--gap) * -1) +
      var(--toast-swipe-movement-y)
  );
  position: absolute;
  right: 0;
  margin: 0 auto;
  box-sizing: border-box;
  width: 100%;
  border: 1px solid oklch(14.5% 0 0deg);
  background-color: white;
  color: oklch(14.5% 0 0deg);
  box-shadow: 0.25rem 0.25rem 0 rgb(0 0 0 / 12%);
  transform-origin: bottom center;
  bottom: 0;
  left: auto;
  margin-right: 0;
  -webkit-user-select: none;
  user-select: none;
  transition:
    transform 0.5s cubic-bezier(0.22, 1, 0.36, 1),
    opacity 0.5s,
    height 0.15s;
  cursor: default;
  z-index: calc(1000 - var(--toast-index));
  height: var(--height);
  transform: translateX(var(--toast-swipe-movement-x))
    translateY(
      calc(
        var(--toast-swipe-movement-y) - (var(--toast-index) * var(--peek)) -
          (var(--shrink) * var(--height))
      )
    )
    scale(var(--scale));

  @media (prefers-color-scheme: dark) {
    border: 1px solid white;
    background-color: oklch(14.5% 0 0deg);
    color: white;
    box-shadow: none;
  }

  &[data-expanded] {
    transform: translateX(var(--toast-swipe-movement-x)) translateY(var(--offset-y));
    height: var(--toast-height);
  }

  &[data-starting-style],
  &[data-ending-style] {
    transform: translateY(150%);
  }

  &[data-limited] {
    opacity: 0;
  }

  &[data-ending-style] {
    opacity: 0;

    &[data-swipe-direction='up'] {
      transform: translateY(calc(var(--toast-swipe-movement-y) - 150%));
    }
    &[data-swipe-direction='left'] {
      transform: translateX(calc(var(--toast-swipe-movement-x) - 150%)) translateY(var(--offset-y));
    }
    &[data-swipe-direction='right'] {
      transform: translateX(calc(var(--toast-swipe-movement-x) + 150%)) translateY(var(--offset-y));
    }
    &[data-swipe-direction='down'] {
      transform: translateY(calc(var(--toast-swipe-movement-y) + 150%));
    }
  }

  &::after {
    content: '';
    position: absolute;
    width: 100%;
    top: 100%;
    left: 0;
    height: calc(var(--gap) + 1px);
  }

  &[data-type='success'] .Text {
    color: oklch(52.7% 0.154 150.069deg);

    @media (prefers-color-scheme: dark) {
      color: oklch(79.2% 0.209 151.711deg);
    }
  }

  &[data-type='error'] .Text {
    color: oklch(50.5% 0.213 27.518deg);

    @media (prefers-color-scheme: dark) {
      color: oklch(70.4% 0.191 22.216deg);
    }
  }

  &:focus-visible {
    outline: 2px solid oklch(14.5% 0 0deg);
    outline-offset: -1px;

    @media (prefers-color-scheme: dark) {
      outline-color: white;
    }
  }
}

.Content {
  box-sizing: border-box;
  display: flex;
  align-items: center;
  gap: 1rem;
  padding: 0.75rem;
  overflow: hidden;
  transition: opacity 0.25s cubic-bezier(0.22, 1, 0.36, 1);

  &[data-behind] {
    opacity: 0;
  }

  &[data-expanded] {
    opacity: 1;
  }
}

.Text {
  display: flex;
  flex-direction: column;
  gap: 0.25rem;
  min-width: 0;
  flex: 1;
}

.Title {
  font-weight: 700;
  font-size: 0.875rem;
  line-height: 1.25rem;
  margin: 0;
}

.Description {
  font-size: 0.875rem;
  line-height: 1.25rem;
  margin: 0;
}

.Close {
  display: flex;
  flex-shrink: 0;
  align-items: center;
  justify-content: center;
  gap: 0.5rem;
  height: 2rem;
  padding: 0 0.75rem;
  border: 1px solid oklch(14.5% 0 0deg);
  border-radius: 0;
  background-color: white;
  color: oklch(14.5% 0 0deg);
  font-family: inherit;
  font-size: 0.875rem;
  font-weight: 400;
  line-height: 1;
  white-space: nowrap;

  @media (prefers-color-scheme: dark) {
    border: 1px solid white;
    background-color: oklch(14.5% 0 0deg);
    color: white;
  }

  @media (hover: hover) {
    &:hover:not([data-disabled]) {
      background-color: oklch(97% 0 0deg);

      @media (prefers-color-scheme: dark) {
        background-color: oklch(26.9% 0 0deg);
      }
    }
  }

  &:active:not([data-disabled]) {
    background-color: oklch(92.2% 0 0deg);

    @media (prefers-color-scheme: dark) {
      background-color: oklch(37.1% 0 0deg);
    }
  }

  &[data-disabled] {
    color: oklch(55.6% 0 0deg);
    border-color: oklch(55.6% 0 0deg);

    @media (prefers-color-scheme: dark) {
      color: oklch(70.8% 0 0deg);
      border-color: oklch(70.8% 0 0deg);
    }
  }

  &:focus-visible {
    outline: 2px solid oklch(14.5% 0 0deg);
    outline-offset: -1px;

    @media (prefers-color-scheme: dark) {
      outline-color: white;
    }
  }
}

.Button {
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0.5rem;
  height: 2rem;
  padding: 0 0.75rem;
  margin: 0;
  border: 1px solid oklch(14.5% 0 0deg);
  border-radius: 0;
  background-color: white;
  font-family: inherit;
  font-size: 0.875rem;
  font-weight: 400;
  line-height: 1;
  white-space: nowrap;
  color: oklch(14.5% 0 0deg);
  -webkit-user-select: none;
  user-select: none;

  @media (prefers-color-scheme: dark) {
    border: 1px solid white;
    background-color: oklch(14.5% 0 0deg);
    color: white;
  }

  @media (hover: hover) {
    &:hover {
      background-color: oklch(97% 0 0deg);

      @media (prefers-color-scheme: dark) {
        background-color: oklch(26.9% 0 0deg);
      }
    }
  }

  &:active {
    background-color: oklch(92.2% 0 0deg);

    @media (prefers-color-scheme: dark) {
      background-color: oklch(37.1% 0 0deg);
    }
  }

  &:focus-visible {
    outline: 2px solid oklch(14.5% 0 0deg);
    outline-offset: -1px;

    @media (prefers-color-scheme: dark) {
      outline-color: white;
    }
  }
}
/* index.tsx */
'use client';
import * as React from 'react';
import { Toast } from '@base-ui/react/toast';
import styles from './index.module.css';

export default function PromiseToastExample() {
  return (
    <Toast.Provider>
      <PromiseDemo />
      <Toast.Portal>
        <Toast.Viewport className={styles.Viewport}>
          <ToastList />
        </Toast.Viewport>
      </Toast.Portal>
    </Toast.Provider>
  );
}

function PromiseDemo() {
  const toastManager = Toast.useToastManager();

  function runPromise() {
    toastManager.promise(
      // Simulate an API request with a promise that resolves after 2 seconds
      new Promise<string>((resolve, reject) => {
        const shouldSucceed = Math.random() > 0.3; // 70% success rate
        setTimeout(() => {
          if (shouldSucceed) {
            resolve('operation completed');
          } else {
            reject(new Error('operation failed'));
          }
        }, 2000);
      }),
      {
        loading: 'Loading data…',
        success: (data: string) => `Success: ${data}`,
        error: (err: Error) => `Error: ${err.message}`,
      },
    );
  }

  return (
    <button type="button" onClick={runPromise} className={styles.Button}>
      Run promise
    </button>
  );
}

function ToastList() {
  const { toasts } = Toast.useToastManager();
  return toasts.map((toast) => (
    <Toast.Root key={toast.id} toast={toast} className={styles.Toast}>
      <Toast.Content className={styles.Content}>
        <div className={styles.Text}>
          <Toast.Title className={styles.Title} />
          <Toast.Description className={styles.Description} />
        </div>
        <Toast.Close className={styles.Close}>Dismiss</Toast.Close>
      </Toast.Content>
    </Toast.Root>
  ));
}

Custom

data 옵션에 어떤 타입의 객체 인터페이스든 전달하면 커스텀 데이터가 있는 토스트를 만들 수 있어요. 이렇게 하면 필요한 모든 데이터(함수 포함)를 토스트에 전달하고 토스트의 렌더링 로직에서 접근할 수 있어요.

Demo

CSS Modules

이 예시는 CSS Modules를 사용해 컴포넌트를 구현하는 방법을 보여줄게요.

/* index.module.css */
.Viewport {
  position: fixed;
  z-index: 1;
  width: calc(100vw - 2rem);
  margin: 0 auto;
  bottom: 1rem;
  right: 1rem;
  left: auto;
  top: auto;

  @media (min-width: 500px) {
    bottom: 2rem;
    right: 2rem;
    width: 22.5rem;
  }
}

.Toast {
  --gap: 0.75rem;
  --peek: 0.75rem;
  --scale: calc(max(0, 1 - (var(--toast-index) * 0.1)));
  --shrink: calc(1 - var(--scale));
  --height: var(--toast-frontmost-height, var(--toast-height));
  --offset-y: calc(
    var(--toast-offset-y) * -1 + (var(--toast-index) * var(--gap) * -1) +
      var(--toast-swipe-movement-y)
  );
  position: absolute;
  right: 0;
  margin: 0 auto;
  box-sizing: border-box;
  width: 100%;
  border: 1px solid oklch(14.5% 0 0deg);
  background-color: white;
  color: oklch(14.5% 0 0deg);
  box-shadow: 0.25rem 0.25rem 0 rgb(0 0 0 / 12%);
  transform-origin: bottom center;
  bottom: 0;
  left: auto;
  margin-right: 0;
  -webkit-user-select: none;
  user-select: none;
  transition:
    transform 0.5s cubic-bezier(0.22, 1, 0.36, 1),
    opacity 0.5s,
    height 0.15s;
  cursor: default;
  z-index: calc(1000 - var(--toast-index));
  height: var(--height);
  transform: translateX(var(--toast-swipe-movement-x))
    translateY(
      calc(
        var(--toast-swipe-movement-y) - (var(--toast-index) * var(--peek)) -
          (var(--shrink) * var(--height))
      )
    )
    scale(var(--scale));

  @media (prefers-color-scheme: dark) {
    border: 1px solid white;
    background-color: oklch(14.5% 0 0deg);
    color: white;
    box-shadow: none;
  }

  &[data-expanded] {
    transform: translateX(var(--toast-swipe-movement-x)) translateY(var(--offset-y));
    height: var(--toast-height);
  }

  &[data-starting-style],
  &[data-ending-style] {
    transform: translateY(150%);
  }

  &[data-limited] {
    opacity: 0;
  }

  &[data-ending-style] {
    opacity: 0;

    &[data-swipe-direction='up'] {
      transform: translateY(calc(var(--toast-swipe-movement-y) - 150%));
    }
    &[data-swipe-direction='left'] {
      transform: translateX(calc(var(--toast-swipe-movement-x) - 150%)) translateY(var(--offset-y));
    }
    &[data-swipe-direction='right'] {
      transform: translateX(calc(var(--toast-swipe-movement-x) + 150%)) translateY(var(--offset-y));
    }
    &[data-swipe-direction='down'] {
      transform: translateY(calc(var(--toast-swipe-movement-y) + 150%));
    }
  }

  &::after {
    content: '';
    position: absolute;
    top: 100%;
    width: 100%;
    left: 0;
    height: calc(var(--gap) + 1px);
  }

  &:focus-visible {
    outline: 2px solid oklch(14.5% 0 0deg);
    outline-offset: -1px;

    @media (prefers-color-scheme: dark) {
      outline-color: white;
    }
  }
}

.Content {
  box-sizing: border-box;
  display: flex;
  align-items: center;
  gap: 1rem;
  padding: 0.75rem;
  overflow: hidden;
  transition: opacity 0.25s cubic-bezier(0.22, 1, 0.36, 1);

  &[data-behind] {
    opacity: 0;
  }

  &[data-expanded] {
    opacity: 1;
  }
}

.Text {
  display: flex;
  flex-direction: column;
  gap: 0.25rem;
  min-width: 0;
  flex: 1;
}

.Title {
  font-weight: 700;
  font-size: 0.875rem;
  line-height: 1.25rem;
  margin: 0;
}

.Description {
  font-size: 0.875rem;
  line-height: 1.25rem;
  margin: 0;
}

.Close {
  display: flex;
  flex-shrink: 0;
  align-items: center;
  justify-content: center;
  gap: 0.5rem;
  height: 2rem;
  padding: 0 0.75rem;
  border: 1px solid oklch(14.5% 0 0deg);
  border-radius: 0;
  background-color: white;
  color: oklch(14.5% 0 0deg);
  font-family: inherit;
  font-size: 0.875rem;
  font-weight: 400;
  line-height: 1;
  white-space: nowrap;

  @media (prefers-color-scheme: dark) {
    border: 1px solid white;
    background-color: oklch(14.5% 0 0deg);
    color: white;
  }

  @media (hover: hover) {
    &:hover:not([data-disabled]) {
      background-color: oklch(97% 0 0deg);

      @media (prefers-color-scheme: dark) {
        background-color: oklch(26.9% 0 0deg);
      }
    }
  }

  &:active:not([data-disabled]) {
    background-color: oklch(92.2% 0 0deg);

    @media (prefers-color-scheme: dark) {
      background-color: oklch(37.1% 0 0deg);
    }
  }

  &[data-disabled] {
    color: oklch(55.6% 0 0deg);
    border-color: oklch(55.6% 0 0deg);

    @media (prefers-color-scheme: dark) {
      color: oklch(70.8% 0 0deg);
      border-color: oklch(70.8% 0 0deg);
    }
  }

  &:focus-visible {
    outline: 2px solid oklch(14.5% 0 0deg);
    outline-offset: -1px;

    @media (prefers-color-scheme: dark) {
      outline-color: white;
    }
  }
}

.Button {
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0.5rem;
  height: 2rem;
  padding: 0 0.75rem;
  margin: 0;
  border: 1px solid oklch(14.5% 0 0deg);
  border-radius: 0;
  background-color: white;
  font-family: inherit;
  font-size: 0.875rem;
  font-weight: 400;
  line-height: 1;
  white-space: nowrap;
  color: oklch(14.5% 0 0deg);
  -webkit-user-select: none;
  user-select: none;

  @media (prefers-color-scheme: dark) {
    border: 1px solid white;
    background-color: oklch(14.5% 0 0deg);
    color: white;
  }

  @media (hover: hover) {
    &:hover {
      background-color: oklch(97% 0 0deg);

      @media (prefers-color-scheme: dark) {
        background-color: oklch(26.9% 0 0deg);
      }
    }
  }

  &:active {
    background-color: oklch(92.2% 0 0deg);

    @media (prefers-color-scheme: dark) {
      background-color: oklch(37.1% 0 0deg);
    }
  }

  &:focus-visible {
    outline: 2px solid oklch(14.5% 0 0deg);
    outline-offset: -1px;

    @media (prefers-color-scheme: dark) {
      outline-color: white;
    }
  }
}
/* index.tsx */
'use client';
import * as React from 'react';
import { Toast } from '@base-ui/react/toast';
import styles from './index.module.css';

interface CustomToastData {
  userId: string;
}

function isCustomToast(
  toast: Toast.Root.ToastObject,
): toast is Toast.Root.ToastObject<CustomToastData> {
  return toast.data?.userId !== undefined;
}

export default function CustomToastExample() {
  return (
    <Toast.Provider>
      <CustomToast />
      <Toast.Portal>
        <Toast.Viewport className={styles.Viewport}>
          <ToastList />
        </Toast.Viewport>
      </Toast.Portal>
    </Toast.Provider>
  );
}

function CustomToast() {
  const toastManager = Toast.useToastManager();

  function action() {
    const data: CustomToastData = {
      userId: '123',
    };

    toastManager.add({
      title: 'Toast with custom data',
      data,
    });
  }

  return (
    <button type="button" onClick={action} className={styles.Button}>
      Create custom toast
    </button>
  );
}

function ToastList() {
  const { toasts } = Toast.useToastManager();
  return toasts.map((toast) => (
    <Toast.Root key={toast.id} toast={toast} className={styles.Toast}>
      <Toast.Content className={styles.Content}>
        <div className={styles.Text}>
          <Toast.Title className={styles.Title}>{toast.title}</Toast.Title>
          {isCustomToast(toast) && toast.data ? (
            <Toast.Description className={styles.Description}>
              data.userId is {toast.data.userId}
            </Toast.Description>
          ) : (
            <Toast.Description className={styles.Description} />
          )}
        </div>
        <Toast.Close className={styles.Close}>Dismiss</Toast.Close>
      </Toast.Content>
    </Toast.Root>
  ));
}

Deduplicated toast

같은 id로 동일한 토스트를 upsert하면 updateKey 속성이 증가해 커스텀 렌더러가 시각적 애니메이션을 다시 재생할 수 있어요. 이 데모는 updateKey에 따라 CSS 애니메이션 이름을 번갈아 사용해, 같은 토스트를 마운트한 상태로 두고 펄스 효과를 재생해요.

Demo

CSS Modules

이 예시는 CSS Modules를 사용해 컴포넌트를 구현하는 방법을 보여줄게요.

/* index.module.css */
.Viewport {
  position: fixed;
  z-index: 1;
  width: calc(100vw - 2rem);
  margin: 0 auto;
  right: 1rem;
  bottom: 1rem;
  left: auto;
  top: auto;

  @media (min-width: 500px) {
    right: 2rem;
    bottom: 2rem;
    width: 22.5rem;
  }
}

.Toast {
  --gap: 0.75rem;
  --peek: 0.75rem;
  --scale: calc(max(0, 1 - (var(--toast-index) * 0.1)));
  --shrink: calc(1 - var(--scale));
  --height: var(--toast-frontmost-height, var(--toast-height));
  --offset-y: calc(
    var(--toast-offset-y) * -1 + (var(--toast-index) * var(--gap) * -1) +
      var(--toast-swipe-movement-y)
  );
  position: absolute;
  right: 0;
  margin: 0 auto;
  box-sizing: border-box;
  width: 100%;
  border: 1px solid oklch(14.5% 0 0deg);
  background-color: white;
  color: oklch(14.5% 0 0deg);
  box-shadow: 0.25rem 0.25rem 0 rgb(0 0 0 / 12%);
  transform-origin: bottom center;
  bottom: 0;
  left: auto;
  margin-right: 0;
  -webkit-user-select: none;
  user-select: none;
  transition:
    transform 0.5s cubic-bezier(0.22, 1, 0.36, 1),
    opacity 0.5s,
    height 0.15s;
  cursor: default;
  z-index: calc(1000 - var(--toast-index));
  height: var(--height);
  transform: translateX(var(--toast-swipe-movement-x))
    translateY(
      calc(
        var(--toast-swipe-movement-y) - (var(--toast-index) * var(--peek)) -
          (var(--shrink) * var(--height))
      )
    )
    scale(var(--scale));

  @media (prefers-color-scheme: dark) {
    border: 1px solid white;
    background-color: oklch(14.5% 0 0deg);
    color: white;
    box-shadow: none;
  }

  &[data-expanded] {
    transform: translateX(var(--toast-swipe-movement-x)) translateY(var(--offset-y));
    height: var(--toast-height);
  }

  &[data-starting-style],
  &[data-ending-style] {
    transform: translateY(150%);
  }

  &[data-limited] {
    opacity: 0;
  }

  &[data-ending-style] {
    opacity: 0;

    &[data-swipe-direction='up'] {
      transform: translateY(calc(var(--toast-swipe-movement-y) - 150%));
    }

    &[data-swipe-direction='left'] {
      transform: translateX(calc(var(--toast-swipe-movement-x) - 150%)) translateY(var(--offset-y));
    }

    &[data-swipe-direction='right'] {
      transform: translateX(calc(var(--toast-swipe-movement-x) + 150%)) translateY(var(--offset-y));
    }

    &[data-swipe-direction='down'] {
      transform: translateY(calc(var(--toast-swipe-movement-y) + 150%));
    }
  }

  &::after {
    content: '';
    position: absolute;
    top: 100%;
    left: 0;
    width: 100%;
    height: calc(var(--gap) + 1px);
  }

  &:focus-visible {
    outline: 2px solid oklch(14.5% 0 0deg);
    outline-offset: -1px;

    @media (prefers-color-scheme: dark) {
      outline-color: white;
    }
  }
}

/* Alternate animation names so repeated updates restart the same pulse. */
.PulseEven {
  animation: pulse-even 0.28s ease;
}

.PulseOdd {
  animation: pulse-odd 0.28s ease;
}

.Content {
  box-sizing: border-box;
  display: flex;
  align-items: center;
  gap: 1rem;
  padding: 0.75rem;
  overflow: hidden;
  transition: opacity 0.25s cubic-bezier(0.22, 1, 0.36, 1);

  &[data-behind] {
    opacity: 0;
  }

  &[data-expanded] {
    opacity: 1;
  }
}

.Text {
  display: flex;
  flex-direction: column;
  gap: 0.25rem;
  min-width: 0;
  flex: 1;
}

.Title {
  font-weight: 700;
  font-size: 0.875rem;
  line-height: 1.25rem;
  margin: 0;
}

.Description {
  font-size: 0.875rem;
  line-height: 1.25rem;
  margin: 0;
}

.Close {
  display: flex;
  flex-shrink: 0;
  align-items: center;
  justify-content: center;
  gap: 0.5rem;
  height: 2rem;
  padding: 0 0.75rem;
  border: 1px solid oklch(14.5% 0 0deg);
  border-radius: 0;
  background-color: white;
  color: oklch(14.5% 0 0deg);
  font-family: inherit;
  font-size: 0.875rem;
  font-weight: 400;
  line-height: 1;
  white-space: nowrap;

  @media (prefers-color-scheme: dark) {
    border: 1px solid white;
    background-color: oklch(14.5% 0 0deg);
    color: white;
  }

  @media (hover: hover) {
    &:hover:not([data-disabled]) {
      background-color: oklch(97% 0 0deg);

      @media (prefers-color-scheme: dark) {
        background-color: oklch(26.9% 0 0deg);
      }
    }
  }

  &:active:not([data-disabled]) {
    background-color: oklch(92.2% 0 0deg);

    @media (prefers-color-scheme: dark) {
      background-color: oklch(37.1% 0 0deg);
    }
  }

  &[data-disabled] {
    color: oklch(55.6% 0 0deg);
    border-color: oklch(55.6% 0 0deg);

    @media (prefers-color-scheme: dark) {
      color: oklch(70.8% 0 0deg);
      border-color: oklch(70.8% 0 0deg);
    }
  }

  &:focus-visible {
    outline: 2px solid oklch(14.5% 0 0deg);
    outline-offset: -1px;

    @media (prefers-color-scheme: dark) {
      outline-color: white;
    }
  }
}

.Button {
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0.5rem;
  height: 2rem;
  padding: 0 0.75rem;
  margin: 0;
  border: 1px solid oklch(14.5% 0 0deg);
  border-radius: 0;
  background-color: white;
  font-family: inherit;
  font-size: 0.875rem;
  font-weight: 400;
  line-height: 1;
  white-space: nowrap;
  color: oklch(14.5% 0 0deg);
  -webkit-user-select: none;
  user-select: none;

  @media (prefers-color-scheme: dark) {
    border: 1px solid white;
    background-color: oklch(14.5% 0 0deg);
    color: white;
  }

  @media (hover: hover) {
    &:hover {
      background-color: oklch(97% 0 0deg);

      @media (prefers-color-scheme: dark) {
        background-color: oklch(26.9% 0 0deg);
      }
    }
  }

  &:active {
    background-color: oklch(92.2% 0 0deg);

    @media (prefers-color-scheme: dark) {
      background-color: oklch(37.1% 0 0deg);
    }
  }

  &:focus-visible {
    outline: 2px solid oklch(14.5% 0 0deg);
    outline-offset: -1px;

    @media (prefers-color-scheme: dark) {
      outline-color: white;
    }
  }
}

@keyframes pulse-even {
  0%,
  100% {
    scale: 1;
  }

  50% {
    scale: 1.04;
  }
}

@keyframes pulse-odd {
  0%,
  100% {
    scale: 1;
  }

  50% {
    scale: 1.04;
  }
}
/* index.tsx */
'use client';
import { Toast } from '@base-ui/react/toast';
import styles from './index.module.css';

export default function PulseToast() {
  return (
    <Toast.Provider>
      <PulseToastButton />
      <Toast.Portal>
        <Toast.Viewport className={styles.Viewport}>
          <ToastList />
        </Toast.Viewport>
      </Toast.Portal>
    </Toast.Provider>
  );
}

function PulseToastButton() {
  const toastManager = Toast.useToastManager();

  function createToast() {
    toastManager.add({
      id: 'save-status',
      title: 'Draft saved',
      description: 'Click again while it is visible to replay the pulse.',
    });
  }

  return (
    <button type="button" onClick={createToast} className={styles.Button}>
      Save draft
    </button>
  );
}

function ToastList() {
  const { toasts } = Toast.useToastManager();
  return toasts.map((toast) => <PulseToastItem key={toast.id} toast={toast} />);
}

function PulseToastItem({ toast }: { toast: Toast.Root.ToastObject }) {
  let pulseClassName: string | null = null;

  // New toasts start with `updateKey: 0`, so the first add skips the replay pulse.
  if (toast.updateKey) {
    pulseClassName = toast.updateKey % 2 === 0 ? styles.PulseEven : styles.PulseOdd;
  }

  const className = [styles.Toast, pulseClassName].filter(Boolean).join(' ');

  return (
    <Toast.Root toast={toast} className={className}>
      <Toast.Content className={styles.Content}>
        <div className={styles.Text}>
          <Toast.Title className={styles.Title} />
          <Toast.Description className={styles.Description} />
        </div>
        <Toast.Close className={styles.Close}>Dismiss</Toast.Close>
      </Toast.Content>
    </Toast.Root>
  );
}

Varying heights

높이가 다른 토스트들은 --toast-frontmost-height CSS 변수로 0번 인덱스의 맨 앞 토스트 높이에 모든 토스트 높이를 맞추며 쌓이고, data-behind 속성이 뒤에 있는 토스트의 콘텐츠를 숨겨요. <Toast.Content>를 루트 높이(예: height: 100%)에 맞추는 것은 피하세요. 루트와 함께 크기가 조절되면 루트의 높이 전환이 취소되거든요.

Demo

CSS Modules

이 예시는 CSS Modules를 사용해 컴포넌트를 구현하는 방법을 보여줄게요.

/* index.module.css */
.Viewport {
  position: fixed;
  z-index: 1;
  width: calc(100vw - 2rem);
  margin: 0 auto;
  bottom: 1rem;
  right: 1rem;
  left: auto;
  top: auto;

  @media (min-width: 500px) {
    bottom: 2rem;
    right: 2rem;
    width: 22.5rem;
  }
}

.Toast {
  --gap: 0.75rem;
  --peek: 0.75rem;
  --scale: calc(max(0, 1 - (var(--toast-index) * 0.1)));
  --shrink: calc(1 - var(--scale));
  --height: var(--toast-frontmost-height, var(--toast-height));
  --offset-y: calc(
    var(--toast-offset-y) * -1 + (var(--toast-index) * var(--gap) * -1) +
      var(--toast-swipe-movement-y)
  );
  position: absolute;
  right: 0;
  margin: 0 auto;
  box-sizing: border-box;
  width: 100%;
  border: 1px solid oklch(14.5% 0 0deg);
  background-color: white;
  color: oklch(14.5% 0 0deg);
  box-shadow: 0.25rem 0.25rem 0 rgb(0 0 0 / 12%);
  transform-origin: bottom center;
  bottom: 0;
  left: auto;
  margin-right: 0;
  -webkit-user-select: none;
  user-select: none;
  transition:
    transform 0.5s cubic-bezier(0.22, 1, 0.36, 1),
    opacity 0.5s,
    height 0.15s;
  cursor: default;
  z-index: calc(1000 - var(--toast-index));
  height: var(--height);
  transform: translateX(var(--toast-swipe-movement-x))
    translateY(
      calc(
        var(--toast-swipe-movement-y) - (var(--toast-index) * var(--peek)) -
          (var(--shrink) * var(--height))
      )
    )
    scale(var(--scale));

  @media (prefers-color-scheme: dark) {
    border: 1px solid white;
    background-color: oklch(14.5% 0 0deg);
    color: white;
    box-shadow: none;
  }

  &[data-expanded] {
    transform: translateX(var(--toast-swipe-movement-x)) translateY(var(--offset-y));
    height: var(--toast-height);
  }

  &[data-starting-style],
  &[data-ending-style] {
    transform: translateY(150%);
  }

  &[data-limited] {
    opacity: 0;
  }

  &[data-ending-style] {
    opacity: 0;

    &[data-swipe-direction='up'] {
      transform: translateY(calc(var(--toast-swipe-movement-y) - 150%));
    }
    &[data-swipe-direction='left'] {
      transform: translateX(calc(var(--toast-swipe-movement-x) - 150%)) translateY(var(--offset-y));
    }
    &[data-swipe-direction='right'] {
      transform: translateX(calc(var(--toast-swipe-movement-x) + 150%)) translateY(var(--offset-y));
    }
    &[data-swipe-direction='down'] {
      transform: translateY(calc(var(--toast-swipe-movement-y) + 150%));
    }
  }

  &::after {
    content: '';
    position: absolute;
    width: 100%;
    top: 100%;
    left: 0;
    height: calc(var(--gap) + 1px);
  }

  &:focus-visible {
    outline: 2px solid oklch(14.5% 0 0deg);
    outline-offset: -1px;

    @media (prefers-color-scheme: dark) {
      outline-color: white;
    }
  }
}

.Content {
  box-sizing: border-box;
  display: flex;
  align-items: center;
  gap: 1rem;
  padding: 0.75rem;
  overflow: hidden;
  transition: opacity 0.25s cubic-bezier(0.22, 1, 0.36, 1);

  &[data-behind] {
    opacity: 0;
  }

  &[data-expanded] {
    opacity: 1;
  }
}

.Text {
  display: flex;
  flex-direction: column;
  gap: 0.25rem;
  min-width: 0;
  flex: 1;
}

.Title {
  font-weight: 700;
  font-size: 0.875rem;
  line-height: 1.25rem;
  margin: 0;
}

.Description {
  font-size: 0.875rem;
  line-height: 1.25rem;
  margin: 0;
}

.Close {
  display: flex;
  flex-shrink: 0;
  align-items: center;
  justify-content: center;
  gap: 0.5rem;
  height: 2rem;
  padding: 0 0.75rem;
  border: 1px solid oklch(14.5% 0 0deg);
  border-radius: 0;
  background-color: white;
  color: oklch(14.5% 0 0deg);
  font-family: inherit;
  font-size: 0.875rem;
  font-weight: 400;
  line-height: 1;
  white-space: nowrap;

  @media (prefers-color-scheme: dark) {
    border: 1px solid white;
    background-color: oklch(14.5% 0 0deg);
    color: white;
  }

  @media (hover: hover) {
    &:hover:not([data-disabled]) {
      background-color: oklch(97% 0 0deg);

      @media (prefers-color-scheme: dark) {
        background-color: oklch(26.9% 0 0deg);
      }
    }
  }

  &:active:not([data-disabled]) {
    background-color: oklch(92.2% 0 0deg);

    @media (prefers-color-scheme: dark) {
      background-color: oklch(37.1% 0 0deg);
    }
  }

  &[data-disabled] {
    color: oklch(55.6% 0 0deg);
    border-color: oklch(55.6% 0 0deg);

    @media (prefers-color-scheme: dark) {
      color: oklch(70.8% 0 0deg);
      border-color: oklch(70.8% 0 0deg);
    }
  }

  &:focus-visible {
    outline: 2px solid oklch(14.5% 0 0deg);
    outline-offset: -1px;

    @media (prefers-color-scheme: dark) {
      outline-color: white;
    }
  }
}

.Button {
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0.5rem;
  height: 2rem;
  padding: 0 0.75rem;
  margin: 0;
  border: 1px solid oklch(14.5% 0 0deg);
  border-radius: 0;
  background-color: white;
  font-family: inherit;
  font-size: 0.875rem;
  font-weight: 400;
  line-height: 1;
  white-space: nowrap;
  color: oklch(14.5% 0 0deg);
  -webkit-user-select: none;
  user-select: none;

  @media (prefers-color-scheme: dark) {
    border: 1px solid white;
    background-color: oklch(14.5% 0 0deg);
    color: white;
  }

  @media (hover: hover) {
    &:hover {
      background-color: oklch(97% 0 0deg);

      @media (prefers-color-scheme: dark) {
        background-color: oklch(26.9% 0 0deg);
      }
    }
  }

  &:active {
    background-color: oklch(92.2% 0 0deg);

    @media (prefers-color-scheme: dark) {
      background-color: oklch(37.1% 0 0deg);
    }
  }

  &:focus-visible {
    outline: 2px solid oklch(14.5% 0 0deg);
    outline-offset: -1px;

    @media (prefers-color-scheme: dark) {
      outline-color: white;
    }
  }
}
/* index.tsx */
'use client';
import * as React from 'react';
import { Toast } from '@base-ui/react/toast';
import styles from './index.module.css';

export default function VaryingHeightsToast() {
  return (
    <Toast.Provider>
      <ToastButton />
      <Toast.Portal>
        <Toast.Viewport className={styles.Viewport}>
          <ToastList />
        </Toast.Viewport>
      </Toast.Portal>
    </Toast.Provider>
  );
}

function ToastButton() {
  const toastManager = Toast.useToastManager();
  const [count, setCount] = React.useState(0);

  function createToast() {
    setCount((prev) => prev + 1);
    const description = TEXTS[Math.floor(Math.random() * TEXTS.length)];
    toastManager.add({
      title: `Toast ${count + 1} created`,
      description,
    });
  }

  return (
    <button type="button" className={styles.Button} onClick={createToast}>
      Create varying height toast
    </button>
  );
}

function ToastList() {
  const { toasts } = Toast.useToastManager();
  return toasts.map((toast) => (
    <Toast.Root key={toast.id} toast={toast} className={styles.Toast}>
      <Toast.Content className={styles.Content}>
        <div className={styles.Text}>
          <Toast.Title className={styles.Title} />
          <Toast.Description className={styles.Description} />
        </div>
        <Toast.Close className={styles.Close}>Dismiss</Toast.Close>
      </Toast.Content>
    </Toast.Root>
  ));
}

const TEXTS = [
  'Short message.',
  'A bit longer message that spans two lines.',
  'This is a longer description that intentionally takes more vertical space to demonstrate stacking with varying heights.',
  'An even longer description that should span multiple lines so we can verify the clamped collapsed height and smooth expansion animation when hovering or focusing the viewport.',
];

API reference

Root

개별 토스트의 모든 부분을 그룹으로 묶어요. <div> 요소를 렌더링해요.

Root Props:

Prop Type Default Description
swipeDirection 'up' | 'down' | 'left' | 'right' | ('left' | 'right' | 'up' | 'down')[] ['down', 'right'] Direction(s) in which the toast can be swiped to dismiss.
toast* Toast.Root.ToastObject - The toast to render.
className string | ((state: Toast.Root.State) => string | undefined) - CSS class applied to the element, or a function that returns a class based on the component's state.
style React.CSSProperties | ((state: Toast.Root.State) => React.CSSProperties | undefined) - Style applied to the element, or a function that returns a style object based on the component's state.
render ReactElement | ((props: HTMLProps, state: Toast.Root.State) => ReactElement) - Allows you to replace the component's HTML element with a different tag, or compose it with another component. Accepts a ReactElement or a function that returns the element to render.

Root Data Attributes:

Attribute Type Description
data-expanded boolean Present when the toast is expanded in the viewport.
data-limited boolean Present when the toast was limited because the toast limit was exceeded.
data-swipe-direction 'up' | 'down' | 'left' | 'right' The direction the toast was swiped.
data-swiping boolean Present when the toast is being swiped.
data-type string The type of the toast.
data-starting-style - Present when the toast begins animating in.
data-ending-style - Present when the toast is animating out.

Root CSS Variables:

Variable Type Description
--toast-height number Indicates the measured natural height of the toast in pixels.
--toast-index number Indicates the index of the toast in the list.
--toast-offset-y number Indicates the vertical pixels offset of the toast in the list when expanded.
--toast-swipe-movement-x number Indicates the horizontal swipe movement of the toast.
--toast-swipe-movement-y number Indicates the vertical swipe movement of the toast.

Root.Props

Root props의 재-export예요.

Root.State

type ToastRootState = {
  /** The transition status of the component. */
  transitionStatus: TransitionStatus;
  /** Whether the toasts in the viewport are expanded. */
  expanded: boolean;
  /** Whether the toast was limited because the toast limit was exceeded. */
  limited: boolean;
  /** The type of the toast. */
  type: string | undefined;
  /** Whether the toast is being swiped. */
  swiping: boolean;
  /** The direction the toast is being swiped. */
  swipeDirection: 'up' | 'down' | 'left' | 'right' | undefined;
};

Root.ToastObject

type ToastRootToastObject<Data extends {} = any> = {
  /** The unique identifier for the toast. */
  id: string;
  /** The ref for the toast. */
  ref?: React.RefObject<HTMLElement | null>;
  /** The title of the toast. */
  title?: React.ReactNode;
  /**
   * The type of the toast. Used to conditionally style the toast,
   * including conditionally rendering elements based on the type.
   */
  type?: string;
  /** The description of the toast. */
  description?: React.ReactNode;
  /**
   * The amount of time (in ms) before the toast is auto dismissed.
   * A value of `0` will prevent the toast from being dismissed automatically.
   * @default 5000
   */
  timeout?: number;
  /**
   * The priority of the toast.
   * - `low` - The toast will be announced politely.
   * - `high` - The toast will be announced urgently.
   * @default 'low'
   */
  priority?: 'low' | 'high';
  /** The transition status of the toast. */
  transitionStatus?: 'starting' | 'ending';
  /** A counter that increments whenever the toast is updated or upserted. */
  updateKey?: number;
  /** Determines if the toast was limited because the toast limit was exceeded. */
  limited?: boolean;
  /** The height of the toast. */
  height?: number;
  /** Callback function to be called when the toast is closed. */
  onClose?: () => void;
  /** Callback function to be called when the toast is removed from the list after any animations are complete when closed. */
  onRemove?: () => void;
  /** The props for the action button. */
  actionProps?: Omit<
    React.DetailedHTMLProps<React.ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement>,
    'ref'
  >;
  /** The props forwarded to the toast positioner element when rendering anchored toasts. */
  positionerProps?: ToastManagerPositionerProps;
  /** Custom data for the toast. */
  data?: Data;
};

Provider

토스트를 만들고 관리하기 위한 컨텍스트를 제공해요.

Provider Props:

Prop Type Default Description
limit number 3 The maximum number of toasts that can be displayed at once. When the limit is exceeded, the oldest toasts are marked as limited (via the data-limited attribute) rather than removed, so they can be hidden or animated out.
toastManager ToastManager - A global manager for toasts to use outside of a React component.
timeout number 5000 The default amount of time (in ms) before a toast is auto dismissed. A value of 0 will prevent the toast from being dismissed automatically.
children React.ReactNode - -

Provider.Props

Provider props의 재-export예요.

Provider.State

type ToastProviderState = {};

Portal

viewport를 DOM의 다른 부분으로 옮기는 portal 요소예요. 기본적으로 portal 요소는 <body>에 추가돼요. <div> 요소를 렌더링해요.

Portal Props:

Prop Type Default Description
container HTMLElement | ShadowRoot | React.RefObject<HTMLElement | ShadowRoot | null> | null - A parent element to render the portal element into.
className string | ((state: Toast.Portal.State) => string | undefined) - CSS class applied to the element, or a function that returns a class based on the component's state.
style React.CSSProperties | ((state: Toast.Portal.State) => React.CSSProperties | undefined) - Style applied to the element, or a function that returns a style object based on the component's state.
render ReactElement | ((props: HTMLProps, state: Toast.Portal.State) => ReactElement) - Allows you to replace the component's HTML element with a different tag, or compose it with another component. Accepts a ReactElement or a function that returns the element to render.

Portal.Props

Portal props의 재-export예요.

Portal.State

type ToastPortalState = {};

Positioner

토스트를 anchor에 대해 배치해요. <div> 요소를 렌더링해요.

Positioner Props:

Prop Type Default Description
disableAnchorTracking boolean false Whether to disable the popup from tracking any layout shift of its positioning anchor.
toast* ToastObject<any> - The toast object associated with the positioner.
align Align 'center' How to align the popup relative to the specified side.
alignOffset number | OffsetFunction 0 Additional offset along the alignment axis in pixels. Also accepts a function that returns the offset to read the dimensions of the anchor and positioner elements, along with its side and alignment. The function takes a data object parameter with the following properties: data.anchor: the dimensions of the anchor element with properties width and height.data.positioner: the dimensions of the positioner element with properties width and height.data.side: which side of the anchor element the positioner is aligned against.data.align: how the positioner is aligned relative to the specified side.
side Side 'top' Which side of the anchor element to align the toast against. May automatically change to avoid collisions.
sideOffset number | OffsetFunction 0 Distance between the anchor and the popup in pixels. Also accepts a function that returns the distance to read the dimensions of the anchor and positioner elements, along with its side and alignment. The function takes a data object parameter with the following properties: data.anchor: the dimensions of the anchor element with properties width and height.data.positioner: the dimensions of the positioner element with properties width and height.data.side: which side of the anchor element the positioner is aligned against.data.align: how the positioner is aligned relative to the specified side.
arrowPadding number 5 Minimum distance to maintain between the arrow and the edges of the popup. Use it to prevent the arrow element from hanging out of the rounded corners of a popup.
anchor Element | null - An element to position the toast against.
collisionAvoidance CollisionAvoidance - Determines how to handle collisions when positioning the popup. side controls overflow on the preferred placement axis (top/bottom or left/right): 'flip': keep the requested side when it fits; otherwise try the opposite side (top and bottom, or left and right).'shift': never change side; keep the requested side and move the popup within the clipping boundary so it stays visible.'none': do not correct side-axis overflow. align controls overflow on the alignment axis (start/center/end): 'flip': keep side, but swap start and end when the requested alignment overflows.'shift': keep side and requested alignment, then nudge the popup along the alignment axis to fit.'none': do not correct alignment-axis overflow. fallbackAxisSide controls fallback behavior on the perpendicular axis when the preferred axis cannot fit: 'start': allow perpendicular fallback and try the logical start side first (top before bottom, or left before right in LTR).'end': allow perpendicular fallback and try the logical end side first (bottom before top, or right before left in LTR).'none': do not fallback to the perpendicular axis. When side is 'shift', explicitly setting align only supports 'shift' or 'none'. If align is omitted, it defaults to 'flip'.
collisionBoundary Boundary 'clipping-ancestors' An element or a rectangle that delimits the area that the popup is confined to.
collisionPadding Padding 5 Additional space to maintain from the edge of the collision boundary.
sticky boolean false Whether to maintain the popup in the viewport after the anchor element was scrolled out of view.
positionMethod 'absolute' | 'fixed' 'absolute' Determines which CSS position property to use.
className string | ((state: Toast.Positioner.State) => string | undefined) - CSS class applied to the element, or a function that returns a class based on the component's state.
style React.CSSProperties | ((state: Toast.Positioner.State) => React.CSSProperties | undefined) - Style applied to the element, or a function that returns a style object based on the component's state.
render ReactElement | ((props: HTMLProps, state: Toast.Positioner.State) => ReactElement) - Allows you to replace the component's HTML element with a different tag, or compose it with another component. Accepts a ReactElement or a function that returns the element to render.

alignOffset Prop Example:

<Positioner
  alignOffset={({ side, align, anchor, positioner }) => {
    return side === 'top' || side === 'bottom' ? anchor.width : anchor.height;
  }}
/>

sideOffset Prop Example:

<Positioner
  sideOffset={({ side, align, anchor, positioner }) => {
    return side === 'top' || side === 'bottom' ? anchor.height : anchor.width;
  }}
/>

collisionAvoidance Prop Example:

<Positioner
  collisionAvoidance={{
    side: 'shift',
    align: 'shift',
    fallbackAxisSide: 'none',
  }}
/>

Positioner Data Attributes:

Attribute Type Description
data-anchor-hidden - Present when the anchor is hidden.
data-align 'start' | 'center' | 'end' Indicates how the toast is aligned relative to specified side.
data-side 'top' | 'bottom' | 'left' | 'right' | 'inline-end' | 'inline-start' Indicates which side the toast is positioned relative to the trigger.

Positioner CSS Variables:

Variable Type Description
--anchor-height number The anchor's height.
--anchor-width number The anchor's width.
--available-height number The available height between the anchor and the edge of the viewport.
--available-width number The available width between the anchor and the edge of the viewport.
--transform-origin string The coordinates that this element is anchored to. Used for animations and transitions.

Positioner.Props

Positioner props의 재-export예요.

Positioner.State

type ToastPositionerState = {
  /** The side of the anchor the component is placed on. */
  side: Side;
  /** The alignment of the component relative to the anchor. */
  align: Align;
  /** Whether the anchor element is hidden. */
  anchorHidden: boolean;
};

Arrow

토스트 anchor에 대해 배치된 요소를 표시해요. <div> 요소를 렌더링해요.

Arrow Props:

Prop Type Default Description
className string | ((state: Toast.Arrow.State) => string | undefined) - CSS class applied to the element, or a function that returns a class based on the component's state.
style React.CSSProperties | ((state: Toast.Arrow.State) => React.CSSProperties | undefined) - Style applied to the element, or a function that returns a style object based on the component's state.
render ReactElement | ((props: HTMLProps, state: Toast.Arrow.State) => ReactElement) - Allows you to replace the component's HTML element with a different tag, or compose it with another component. Accepts a ReactElement or a function that returns the element to render.

Arrow Data Attributes:

Attribute Type Description
data-uncentered - Present when the toast arrow is uncentered.
data-align 'start' | 'center' | 'end' Indicates how the toast is aligned relative to specified side.
data-side 'top' | 'bottom' | 'left' | 'right' | 'inline-end' | 'inline-start' Indicates which side the toast is positioned relative to the anchor.

Arrow.Props

Arrow props의 재-export예요.

Arrow.State

type ToastArrowState = {
  /** The side of the anchor the component is placed on. */
  side: Side;
  /** The alignment of the component relative to the anchor. */
  align: Align;
  /** Whether the arrow cannot be centered on the anchor. */
  uncentered: boolean;
};

Content

토스트 콘텐츠를 담는 컨테이너예요. <div> 요소를 렌더링해요.

Content Props:

Prop Type Default Description
className string | ((state: Toast.Content.State) => string | undefined) - CSS class applied to the element, or a function that returns a class based on the component's state.
style React.CSSProperties | ((state: Toast.Content.State) => React.CSSProperties | undefined) - Style applied to the element, or a function that returns a style object based on the component's state.
render ReactElement | ((props: HTMLProps, state: Toast.Content.State) => ReactElement) - Allows you to replace the component's HTML element with a different tag, or compose it with another component. Accepts a ReactElement or a function that returns the element to render.

Content Data Attributes:

Attribute Type Description
data-behind boolean Present when the toast is behind the frontmost toast in the stack.
data-expanded boolean Present when the toast viewport is expanded.

Content.Props

Content props의 재-export예요.

Content.State

type ToastContentState = {
  /** Whether the toast viewport is expanded. */
  expanded: boolean;
  /** Whether the toast is behind the frontmost toast in the stack. */
  behind: boolean;
};

Title

토스트에 라벨을 붙이는 제목이에요. <h2> 요소를 렌더링해요.

Title Props:

Prop Type Default Description
className string | ((state: Toast.Title.State) => string | undefined) - CSS class applied to the element, or a function that returns a class based on the component's state.
style React.CSSProperties | ((state: Toast.Title.State) => React.CSSProperties | undefined) - Style applied to the element, or a function that returns a style object based on the component's state.
render ReactElement | ((props: HTMLProps, state: Toast.Title.State) => ReactElement) - Allows you to replace the component's HTML element with a different tag, or compose it with another component. Accepts a ReactElement or a function that returns the element to render.

Title Data Attributes:

Attribute Type Description
data-type string The type of the toast.

Title.Props

Title props의 재-export예요.

Title.State

type ToastTitleState = {
  /** The type of the toast. */
  type: string | undefined;
};

Description

토스트를 설명하는 설명이에요. 제목이 제공되지 않을 때 토스트의 기본 메시지로 사용할 수 있어요. <p> 요소를 렌더링해요.

Description Props:

Prop Type Default Description
className string | ((state: Toast.Description.State) => string | undefined) - CSS class applied to the element, or a function that returns a class based on the component's state.
style React.CSSProperties | ((state: Toast.Description.State) => React.CSSProperties | undefined) - Style applied to the element, or a function that returns a style object based on the component's state.
render ReactElement | ((props: HTMLProps, state: Toast.Description.State) => ReactElement) - Allows you to replace the component's HTML element with a different tag, or compose it with another component. Accepts a ReactElement or a function that returns the element to render.

Description Data Attributes:

Attribute Type Description
data-type string The type of the toast.

Description.Props

Description props의 재-export예요.

Description.State

type ToastDescriptionState = {
  /** The type of the toast. */
  type: string | undefined;
};

Close

클릭하면 토스트를 닫아요. <button> 요소를 렌더링해요.

Close Props:

Prop Type Default Description
nativeButton boolean true Whether the component renders a native <button> element when replacing it via the render prop. Set to false if the rendered element is not a button (for example, <div>).
className string | ((state: Toast.Close.State) => string | undefined) - CSS class applied to the element, or a function that returns a class based on the component's state.
style React.CSSProperties | ((state: Toast.Close.State) => React.CSSProperties | undefined) - Style applied to the element, or a function that returns a style object based on the component's state.
render ReactElement | ((props: HTMLProps, state: Toast.Close.State) => ReactElement) - Allows you to replace the component's HTML element with a different tag, or compose it with another component. Accepts a ReactElement or a function that returns the element to render.

Close Data Attributes:

Attribute Type Description
data-type string The type of the toast.

Close.Props

Close props의 재-export예요.

Close.State

type ToastCloseState = {
  /** The type of the toast. */
  type: string | undefined;
};

Action

클릭하면 액션을 수행해요. <button> 요소를 렌더링해요.

Action Props:

Prop Type Default Description
nativeButton boolean true Whether the component renders a native <button> element when replacing it via the render prop. Set to false if the rendered element is not a button (for example, <div>).
className string | ((state: Toast.Action.State) => string | undefined) - CSS class applied to the element, or a function that returns a class based on the component's state.
style React.CSSProperties | ((state: Toast.Action.State) => React.CSSProperties | undefined) - Style applied to the element, or a function that returns a style object based on the component's state.
render ReactElement | ((props: HTMLProps, state: Toast.Action.State) => ReactElement) - Allows you to replace the component's HTML element with a different tag, or compose it with another component. Accepts a ReactElement or a function that returns the element to render.

Action Data Attributes:

Attribute Type Description
data-type string The type of the toast.

Action.Props

Action props의 재-export예요.

Action.State

type ToastActionState = {
  /** The type of the toast. */
  type: string | undefined;
};

Viewport

토스트를 위한 컨테이너 viewport예요. <div> 요소를 렌더링해요.

Viewport Props:

Prop Type Default Description
className string | ((state: Toast.Viewport.State) => string | undefined) - CSS class applied to the element, or a function that returns a class based on the component's state.
style React.CSSProperties | ((state: Toast.Viewport.State) => React.CSSProperties | undefined) - Style applied to the element, or a function that returns a style object based on the component's state.
render ReactElement | ((props: HTMLProps, state: Toast.Viewport.State) => ReactElement) - Allows you to replace the component's HTML element with a different tag, or compose it with another component. Accepts a ReactElement or a function that returns the element to render.

Viewport Data Attributes:

Attribute Type Description
data-expanded boolean Indicates toasts are expanded in the viewport.

Viewport CSS Variables:

Variable Type Description
--toast-frontmost-height number Indicates the height of the frontmost toast.

Viewport.Props

Viewport props의 재-export예요.

Viewport.State

type ToastViewportState = {
  /** Whether toasts are expanded in the viewport. */
  expanded: boolean;
};

createToastManager

새 토스트 매니저를 만들어요.

Return Value:

type ReturnValue = ToastManager<{}>;

useToastManager

토스트 배열과 토스트를 관리하는 메서드를 반환해요.

Return Value:

type ReturnValue = UseToastManagerReturnValue<{}>;

Additional Types

ToastObject

type ToastObject<Data extends {}> = {
  /** The unique identifier for the toast. */
  id: string;
  /** The ref for the toast. */
  ref?: React.RefObject<HTMLElement | null>;
  /** The title of the toast. */
  title?: React.ReactNode;
  /**
   * The type of the toast. Used to conditionally style the toast,
   * including conditionally rendering elements based on the type.
   */
  type?: string;
  /** The description of the toast. */
  description?: React.ReactNode;
  /**
   * The amount of time (in ms) before the toast is auto dismissed.
   * A value of `0` will prevent the toast from being dismissed automatically.
   * @default 5000
   */
  timeout?: number;
  /**
   * The priority of the toast.
   * - `low` - The toast will be announced politely.
   * - `high` - The toast will be announced urgently.
   * @default 'low'
   */
  priority?: 'low' | 'high';
  /** The transition status of the toast. */
  transitionStatus?: 'starting' | 'ending';
  /** A counter that increments whenever the toast is updated or upserted. */
  updateKey?: number;
  /** Determines if the toast was limited because the toast limit was exceeded. */
  limited?: boolean;
  /** The height of the toast. */
  height?: number;
  /** Callback function to be called when the toast is closed. */
  onClose?: () => void;
  /** Callback function to be called when the toast is removed from the list after any animations are complete when closed. */
  onRemove?: () => void;
  /** The props for the action button. */
  actionProps?: Omit<
    React.DetailedHTMLProps<React.ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement>,
    'ref'
  >;
  /** The props forwarded to the toast positioner element when rendering anchored toasts. */
  positionerProps?: ToastManagerPositionerProps;
  /** Custom data for the toast. */
  data?: Data;
};

ToastManager

type ToastManager<Data extends {} = any> = {
  ' subscribe': (listener: (data: ToastManagerEvent) => void) => () => void;
  add: <T extends Data = Data>(options: ToastManagerAddOptions<T>) => string;
  close: (id?: string) => void;
  update: <T extends Data = Data>(
    id: string,
    updates:
      ToastManagerUpdateOptions<T> | ((prevToast: ToastObject<T>) => ToastManagerUpdateOptions<T>),
  ) => void;
  promise: <Value, T extends Data = Data>(
    promiseValue: Promise<Value>,
    options: ToastManagerPromiseOptions<Value, T>,
  ) => Promise<Value>;
};

ToastManagerAddOptions

type ToastManagerAddOptions<Data extends {}> = {
  /**
   * The unique identifier for the toast. Adding a toast with an existing ID
   * updates it in place and refreshes its auto-dismiss timer.
   */
  id?: string;
  /** The title of the toast. */
  title?: React.ReactNode;
  /**
   * The type of the toast. Used to conditionally style the toast,
   * including conditionally rendering elements based on the type.
   */
  type?: string;
  /** The description of the toast. */
  description?: React.ReactNode;
  /**
   * The amount of time (in ms) before the toast is auto dismissed.
   * A value of `0` will prevent the toast from being dismissed automatically.
   * @default 5000
   */
  timeout?: number;
  /**
   * The priority of the toast.
   * - `low` - The toast will be announced politely.
   * - `high` - The toast will be announced urgently.
   * @default 'low'
   */
  priority?: 'low' | 'high';
  /** The transition status of the toast. */
  transitionStatus?: 'starting' | 'ending';
  /** Callback function to be called when the toast is closed. */
  onClose?: () => void;
  /** Callback function to be called when the toast is removed from the list after any animations are complete when closed. */
  onRemove?: () => void;
  /** The props for the action button. */
  actionProps?: Omit<
    React.DetailedHTMLProps<React.ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement>,
    'ref'
  >;
  /** The props forwarded to the toast positioner element when rendering anchored toasts. */
  positionerProps?: ToastManagerPositionerProps;
  /** Custom data for the toast. */
  data?: Data;
};

ToastManagerEvent

type ToastManagerEvent = { action: 'add' | 'close' | 'update' | 'promise'; options: any };

ToastManagerPositionerProps

type ToastManagerPositionerProps = {
  /** An element to position the toast against. */
  anchor?: Element | null;
  /**
   * Style applied to the element, or a function that
   * returns a style object based on the component's state.
   */
  style?:
    React.CSSProperties | ((state: Toast.Positioner.State) => React.CSSProperties | undefined);
  /**
   * CSS class applied to the element, or a function that
   * returns a class based on the component's state.
   */
  className?: string | ((state: Toast.Positioner.State) => string | undefined);
  /**
   * Which side of the anchor element to align the toast against.
   * May automatically change to avoid collisions.
   * @default 'top'
   */
  side?: Side;
  /**
   * Determines which CSS `position` property to use.
   * @default 'absolute'
   */
  positionMethod?: 'absolute' | 'fixed';
  /**
   * Distance between the anchor and the popup in pixels.
   * Also accepts a function that returns the distance to read the dimensions of the anchor
   * and positioner elements, along with its side and alignment.
   *
   * The function takes a `data` object parameter with the following properties:
   * - `data.anchor`: the dimensions of the anchor element with properties `width` and `height`.
   * - `data.positioner`: the dimensions of the positioner element with properties `width` and `height`.
   * - `data.side`: which side of the anchor element the positioner is aligned against.
   * - `data.align`: how the positioner is aligned relative to the specified side.
   * @default 0
   * @example
   * ```jsx
   * <Positioner
   *   sideOffset={({ side, align, anchor, positioner }) => {
   *     return side === 'top' || side === 'bottom'
   *       ? anchor.height
   *       : anchor.width;
   *   }}
   * />
   * ```
   */
  sideOffset?: number | OffsetFunction;
  /**
   * How to align the popup relative to the specified side.
   * @default 'center'
   */
  align?: Align;
  /**
   * Additional offset along the alignment axis in pixels.
   * Also accepts a function that returns the offset to read the dimensions of the anchor
   * and positioner elements, along with its side and alignment.
   *
   * The function takes a `data` object parameter with the following properties:
   * - `data.anchor`: the dimensions of the anchor element with properties `width` and `height`.
   * - `data.positioner`: the dimensions of the positioner element with properties `width` and `height`.
   * - `data.side`: which side of the anchor element the positioner is aligned against.
   * - `data.align`: how the positioner is aligned relative to the specified side.
   * @default 0
   * @example
   * ```jsx
   * <Positioner
   *   alignOffset={({ side, align, anchor, positioner }) => {
   *     return side === 'top' || side === 'bottom'
   *       ? anchor.width
   *       : anchor.height;
   *   }}
   * />
   * ```
   */
  alignOffset?: number | OffsetFunction;
  /**
   * An element or a rectangle that delimits the area that the popup is confined to.
   * @default 'clipping-ancestors'
   */
  collisionBoundary?: Boundary;
  /**
   * Additional space to maintain from the edge of the collision boundary.
   * @default 5
   */
  collisionPadding?: Padding;
  /**
   * Whether to maintain the popup in the viewport after
   * the anchor element was scrolled out of view.
   * @default false
   */
  sticky?: boolean;
  /**
   * Minimum distance to maintain between the arrow and the edges of the popup.
   *
   * Use it to prevent the arrow element from hanging out of the rounded corners of a popup.
   * @default 5
   */
  arrowPadding?: number;
  /**
   * Whether to disable the popup from tracking any layout shift of its positioning anchor.
   * @default false
   */
  disableAnchorTracking?: boolean;
  /**
   * Determines how to handle collisions when positioning the popup.
   *
   * `side` controls overflow on the preferred placement axis (`top`/`bottom` or `left`/`right`):
   * - `'flip'`: keep the requested side when it fits; otherwise try the opposite side
   *   (`top` and `bottom`, or `left` and `right`).
   * - `'shift'`: never change side; keep the requested side and move the popup within
   *   the clipping boundary so it stays visible.
   * - `'none'`: do not correct side-axis overflow.
   *
   * `align` controls overflow on the alignment axis (`start`/`center`/`end`):
   * - `'flip'`: keep side, but swap `start` and `end` when the requested alignment overflows.
   * - `'shift'`: keep side and requested alignment, then nudge the popup along the
   *   alignment axis to fit.
   * - `'none'`: do not correct alignment-axis overflow.
   *
   * `fallbackAxisSide` controls fallback behavior on the perpendicular axis when the
   * preferred axis cannot fit:
   * - `'start'`: allow perpendicular fallback and try the logical start side first
   *   (`top` before `bottom`, or `left` before `right` in LTR).
   * - `'end'`: allow perpendicular fallback and try the logical end side first
   *   (`bottom` before `top`, or `right` before `left` in LTR).
   * - `'none'`: do not fallback to the perpendicular axis.
   *
   * When `side` is `'shift'`, explicitly setting `align` only supports `'shift'` or `'none'`.
   * If `align` is omitted, it defaults to `'flip'`.
   * @example
   * ```jsx
   * <Positioner
   *   collisionAvoidance={{
   *     side: 'shift',
   *     align: 'shift',
   *     fallbackAxisSide: 'none',
   *   }}
   * />
   * ```
   */
  collisionAvoidance?: CollisionAvoidance;
  /**
   * Allows you to replace the component's HTML element
   * with a different tag, or compose it with another component.
   *
   * Accepts a `ReactElement` or a function that returns the element to render.
   */
  render?: ReactElement | ((props: HTMLProps, state: Toast.Positioner.State) => ReactElement);
};

ToastManagerPromiseOptions

type ToastManagerPromiseOptions<Value, Data extends {}> = {
  loading: string | ToastManagerUpdateOptions<Data>;
  success:
    | string
    | ToastManagerUpdateOptions<Data>
    | ((result: Value) => string | ToastManagerUpdateOptions<Data>);
  error:
    | string
    | ToastManagerUpdateOptions<Data>
    | ((error: any) => string | ToastManagerUpdateOptions<Data>);
};

ToastManagerUpdateOptions

type ToastManagerUpdateOptions<Data extends {}> = {
  /** The title of the toast. */
  title?: React.ReactNode;
  /**
   * The type of the toast. Used to conditionally style the toast,
   * including conditionally rendering elements based on the type.
   */
  type?: string;
  /** The description of the toast. */
  description?: React.ReactNode;
  /**
   * The amount of time (in ms) before the toast is auto dismissed.
   * A value of `0` will prevent the toast from being dismissed automatically.
   * @default 5000
   */
  timeout?: number;
  /**
   * The priority of the toast.
   * - `low` - The toast will be announced politely.
   * - `high` - The toast will be announced urgently.
   * @default 'low'
   */
  priority?: 'low' | 'high';
  /** Callback function to be called when the toast is closed. */
  onClose?: () => void;
  /** Callback function to be called when the toast is removed from the list after any animations are complete when closed. */
  onRemove?: () => void;
  /** The props for the action button. */
  actionProps?: Omit<
    React.DetailedHTMLProps<React.ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement>,
    'ref'
  >;
  /** The props forwarded to the toast positioner element when rendering anchored toasts. */
  positionerProps?: ToastManagerPositionerProps;
  /** Custom data for the toast. */
  data?: Data;
};

UseToastManagerReturnValue

type UseToastManagerReturnValue<Data extends {} = any> = {
  toasts: ToastObject<Data>[];
  add: <T extends Data = Data>(options: ToastManagerAddOptions<T>) => string;
  close: (toastId?: string) => void;
  update: <T extends Data = Data>(
    toastId: string,
    options:
      ToastManagerUpdateOptions<T> | ((prevToast: ToastObject<T>) => ToastManagerUpdateOptions<T>),
  ) => void;
  promise: <Value, T extends Data = Data>(
    promise: Promise<Value>,
    options: ToastManagerPromiseOptions<Value, T>,
  ) => Promise<Value>;
};

External Types

Side

type Side = 'top' | 'bottom' | 'left' | 'right' | 'inline-end' | 'inline-start';

Align

type Align = 'start' | 'center' | 'end';

OffsetFunction

type OffsetFunction = (data: {
  side: 'top' | 'bottom' | 'left' | 'right' | 'inline-end' | 'inline-start';
  align: 'start' | 'center' | 'end';
  anchor: { width: number; height: number };
  positioner: { width: number; height: number };
}) => number;

Export Groups

  • Toast.Provider: Toast.Provider, Toast.Provider.State, Toast.Provider.Props
  • Toast.Viewport: Toast.Viewport, Toast.Viewport.State, Toast.Viewport.Props
  • Toast.Root: Toast.Root, Toast.Root.ToastObject, Toast.Root.State, Toast.Root.Props
  • Toast.Content: Toast.Content, Toast.Content.State, Toast.Content.Props
  • Toast.Description: Toast.Description, Toast.Description.State, Toast.Description.Props
  • Toast.Title: Toast.Title, Toast.Title.State, Toast.Title.Props
  • Toast.Close: Toast.Close, Toast.Close.State, Toast.Close.Props
  • Toast.Action: Toast.Action, Toast.Action.State, Toast.Action.Props
  • Toast.Portal: Toast.Portal, Toast.Portal.State, Toast.Portal.Props
  • Toast.Positioner: Toast.Positioner, Toast.Positioner.State, Toast.Positioner.Props
  • Toast.Arrow: Toast.Arrow, Toast.Arrow.State, Toast.Arrow.Props
  • Toast.useToastManager
  • Toast.createToastManager
  • Default: ToastRootToastObject, ToastRootState, ToastRootProps, ToastProviderState, ToastProviderProps, ToastViewportState, ToastViewportProps, ToastContentState, ToastContentProps, ToastDescriptionState, ToastDescriptionProps, ToastTitleState, ToastTitleProps, ToastCloseState, ToastCloseProps, ToastActionState, ToastActionProps, ToastPortalState, ToastPortalProps, ToastPositionerState, ToastPositionerProps, ToastArrowState, ToastArrowProps, ToastObject, ToastManagerPositionerProps, UseToastManagerReturnValue, ToastManagerAddOptions, ToastManagerUpdateOptions, ToastManagerPromiseOptions, ToastManager, ToastManagerEvent

Canonical Types

Canonical: Alias 매핑이에요. 네임스페이스가 이미 import되어 있을 때는 Canonical을, 그렇지 않으면 Alias를 사용해요.

  • Toast.Provider.State: ToastProviderState
  • Toast.Provider.Props: ToastProviderProps
  • Toast.Viewport.State: ToastViewportState
  • Toast.Viewport.Props: ToastViewportProps
  • Toast.Root.ToastObject: ToastRootToastObject
  • Toast.Root.State: ToastRootState
  • Toast.Root.Props: ToastRootProps
  • Toast.Content.State: ToastContentState
  • Toast.Content.Props: ToastContentProps
  • Toast.Description.State: ToastDescriptionState
  • Toast.Description.Props: ToastDescriptionProps
  • Toast.Title.State: ToastTitleState
  • Toast.Title.Props: ToastTitleProps
  • Toast.Close.State: ToastCloseState
  • Toast.Close.Props: ToastCloseProps
  • Toast.Action.State: ToastActionState
  • Toast.Action.Props: ToastActionProps
  • Toast.Portal.State: ToastPortalState
  • Toast.Portal.Props: ToastPortalProps
  • Toast.Positioner.State: ToastPositionerState
  • Toast.Positioner.Props: ToastPositionerProps
  • Toast.Arrow.State: ToastArrowState
  • Toast.Arrow.Props: ToastArrowProps

useToastManager

<Toast.Provider> 내부에서 호출되어 토스트를 관리해요.

const toastManager = Toast.useToastManager();

add method

토스트 목록에 추가하여 토스트를 만들어요.

이미 존재하는 id를 전달하면 중복을 만들지 않고 기존 토스트를 그 자리에서 업데이트해요.

나중에 토스트를 업데이트하거나 닫는 데 사용할 수 있는 toastId를 반환해요.

const toastId = toastManager.add({
  description: 'Hello, world!',
});
function App() {
  // @highlight
  const toastManager = Toast.useToastManager();
  return (
    <button
      type="button"
      onClick={() => {
        // @highlight-start
        toastManager.add({
          description: 'Hello, world!',
        });
        // @highlight-end
      }}
    >
      Add toast
    </button>
  );
}

높은 우선순위 토스트의 경우 title과 description 문자열이 스크린 리더에 토스트를 알리는 데 사용돼요. 스크린 리더는 <Toast.Title>이나 <Toast.Description> 컴포넌트를 포함해 <Toast.Root> 안에 렌더링된 추가 콘텐츠를 알리지 않아요. 사용자가 의도적으로 토스트 viewport로 이동하지 않는 한 그렇죠.

update method

새 옵션으로 토스트를 업데이트해요.

toastManager.update(toastId, {
  description: 'New description',
});

옵션은 커스텀 data를 포함해 토스트의 해당 값을 전체적으로 대체해요. 토스트의 현재 상태에서 업데이트를 도출하려면 대신 함수를 전달하세요. 함수는 현재 토스트를 받아 적용할 옵션을 반환해요. 아직 토스트에 data가 없으면 커스텀 data는 undefined예요:

toastManager.update(toastId, (prevToast) => ({
  data: prevToast.data && { ...prevToast.data, progress: 100 },
}));

close method

토스트를 닫아, 애니메이션이 완료된 후 토스트 목록에서 제거해요.

toastManager.close(toastId);

또는 ID를 전달하지 않으면 모든 토스트를 한 번에 닫을 수 있어요:

toastManager.close();

promise method

loading, success, error의 세 가지 상태로 비동기 토스트를 만들어요.

const promise = toastManager.promise(
  new Promise((resolve) => {
    setTimeout(() => resolve('world!'), 1000);
  }),
  {
    // Each are a shortcut for the `description` option
    loading: 'Loading…',
    success: (data) => `Hello ${data}`,
    error: (err) => `Error: ${err}`,
  },
);

각 상태는 상태별로 토스트를 세밀하게 제어하기 위해 method options 객체도 받아요:

const promise = toastManager.promise(
  new Promise((resolve) => {
    setTimeout(() => resolve('world!'), 1000);
  }),
  {
    loading: {
      title: 'Loading…',
      description: 'The promise is loading.',
    },
    success: {
      title: 'Success',
      description: 'The promise resolved successfully.',
    },
    error: {
      title: 'Error',
      description: 'The promise rejected.',
      actionProps: {
        children: 'Contact support',
        onClick() {
          // Redirect to support page
        },
      },
    },
  },
);

전체 promise 메서드 보기

Additional types

더 알아보기 (Learn more)