useToast
토스트 알림 상태, 스와이프 닫기, 자동 타임아웃, 쌓임(stacking) 동작을 관리하는 훅들이에요.
출처: 문서
본문
사용법 (Usage)
import { toast, useToaster } from '@primereact/headless/toaster';
import { useToast } from '@primereact/headless/toast';
const toaster = useToaster({ position: 'bottom-right' });
const { rootProps, regionProps, toasts } = toaster;
const { rootProps: toastRootProps, closeProps, state } = useToast({ toast: toastData, toaster });
<div {...rootProps}>
<div {...regionProps}>
{toasts.map((t) => (
<div {...toastRootProps}>
<button {...closeProps}></button>
</div>
useToaster는 토스트 컨테이너를 관리하고, useToast는 토스트별 수명 주기를 다뤄요. 컴포넌트 기반 API가 필요하다면 Primitive 문서를 참고하세요.
기능 (Features)
- 두 훅 아키텍처,
useToaster가 컨테이너/region 상태를 소유하고,useToast가 토스트별 수명 주기를 다뤄요 - 명령형 API, 전역
toast함수에 severity 단축 메서드(success,info,warn,error,secondary,contrast)와update,dismiss,promise메서드가 붙어 있어요 - 스와이프로 닫기,
data-*수명 주기 속성과 함께 방향성 제스처를 감지해요 - 일시정지 가능한 자동 타임아웃, 호버, 포커스, 문서가 숨겨져 있을 때 타이머가 일시정지돼요. 토스트별
duration이 컨테이너timeout을 덮어써요 - 쌓임과 확장, 호버 시 확장되는 쌓인 레이아웃, 설정 가능한 표시
limit, 위치 배치를 지원해요 - 그룹핑, 일치하는
group키로 토스트를 특정 컨테이너로 라우팅해요
토스트 다루기 (Working with toasts)
토스트 만들기 (Creating toasts)
severity를 직접 넘기거나 단축 메서드를 사용하세요. 각 호출은 나중에 update나 dismiss에 쓸 수 있는 id를 반환해요.
import { toast } from '@primereact/headless/toaster';
const id = toast({ title: 'Update available', description: 'A new version is ready.' });
toast.success({ title: 'Saved' });
toast.error({ title: 'Error', description: 'Something went wrong.' });
Promise 수명 주기 (Promise lifecycle)
toast.promise는 단일 토스트를 promise에 묶어요. await 동안은 loading 상태를 보여주고, 결과에 따라 success나 error로 바뀌죠.
toast.promise(fetchData(), {
loading: { title: 'Loading…' },
success: (data) => ({ title: 'Done', description: `Fetched ${data.length} items.` }),
error: (err) => ({ title: 'Failed', description: err.message })
});
토스트 업데이트 (Updating toasts)
toast.update(id, options)는 기존 토스트에 새 옵션을 병합해요. 주로 로딩 토스트를 결과 토스트로 바꿀 때 씁니다.
const id = toast({ loading: true, title: 'Uploading…' });
await upload();
toast.update(id, { loading: false, severity: 'success', title: 'Complete' });
커스텀 JSX (Custom JSX)
render에 React 요소를 넘기면 기본 바디를 덮어써요. 위치·애니메이션·스와이프를 담당하는 root 래퍼는 그대로 유지돼요.
const id = toast({
render: (
<div>
<span>Custom content</span>
<button onClick={() => toast.dismiss(id)}>Close</button>
</div>
)
});
고정(sticky) 및 그룹화된 토스트 (Sticky and grouped toasts)
duration: Infinity를 넘기면 수동으로 닫을 때까지 토스트가 유지돼요. toaster와 호출 양쪽에 group을 쓰면 토스트를 특정 컨테이너로 라우팅할 수 있어요.
const toaster = useToaster({ group: 'notifications' });
toast({ title: 'Sticky', duration: Infinity, group: 'notifications' });
콜백 (Callbacks)
toast({
title: 'Notification',
onDismiss: (t) => console.log('dismissed', t.id),
onTimeout: (t) => console.log('timed out', t.id)
});
토스트별 상태 (Per-toast state)
useToast는 커스텀 애니메이션이나 조건부 렌더링에 유용한 state 객체를 노출해요.
const { state } = useToast({ toast: toastData, toaster });
// state.mounted, state.removed, state.swiping, state.swipeOut,
// state.swipeOutDirection, state.isSwiped, state.initialHeight
data 속성으로 스타일링 (Styling with data attributes)
두 훅의 rootProps는 data-* 속성으로 상태를 노출해요.
| Scope (Scope) | 요소 (Element) | 속성 (Attributes) |
|---|---|---|
toaster |
region | data-position, data-expanded |
toast |
root | data-mounted, data-removed, data-visible, data-front, data-swiping, data-swipe-out, data-swipe-direction |
[data-position='bottom-right'] {
right: 2rem;
bottom: 2rem;
}
[data-mounted] {
opacity: 1;
}
[data-removed] {
opacity: 0;
}
[data-swiping] {
transition: none;
}
[data-swipe-out][data-swipe-direction='left'] {
transform: translateX(-100%);
}
API
useToaster
useToast
접근성 (Accessibility)
토스트 안에 액션 버튼이 있으면 포커스가 토스트로 들어오고, 포커스된 상태에서 Escape를 누르면 닫혀요. 전체 WAI-ARIA 준수 세부 사항은 Primitive 문서를 참고하세요.