토스트 (Toast)
화면에 나타나 사용자에게 동작에 대한 피드백을 제공하는 메시지 컴포넌트입니다. 성공, 오류, 경고, 정보 등 다양한 유형의 알림을 지원합니다.
출처: 문서
본문
해부 구조 (Anatomy)
const toaster = createToaster({ placement: 'bottom-end' })
<Toaster toaster={toaster}>
{(toast) => (
<Toast.Root>
<Toast.Title />
<Toast.Description />
<Toast.ActionTrigger />
<Toast.CloseTrigger />
</Toast.Root>
)}
</Toaster>
설정 (Setup)
Toast 컴포넌트를 사용하려면 createToaster 함수로 토스트 엔진을 만드세요.
이 함수는 토스트의 위치(placement)와 그룹화를 관리하고, 토스트 알림을 만드는 데 필요한 toast 객체를 제공합니다.
const toaster = createToaster({
placement: 'bottom-end',
overlap: true,
gap: 24,
})
예시 (Examples)
다음은 toast.create 메서드를 사용하여 토스트를 만드는 예시입니다.
import { Portal } from '@ark-ui/react/portal'
import { Toast, Toaster, createToaster } from '@ark-ui/react/toast'
import { XIcon } from 'lucide-react'
import button from 'styles/button.module.css'
import styles from 'styles/toast.module.css'
const toaster = createToaster({
placement: 'bottom-end',
overlap: true,
gap: 24,
})
export const Basic = () => {
return (
<div>
<button
type="button"
className={button.Root}
onClick={() =>
toaster.create({
title: 'Scheduled for tomorrow',
description: 'Your meeting has been scheduled for tomorrow at 10am.',
type: 'info',
})
}
>
Schedule meeting
</button>
<Portal>
<Toaster toaster={toaster}>
{(toast) => (
<Toast.Root key={toast.id} className={styles.Root}>
<Toast.Title className={styles.Title}>{toast.title}</Toast.Title>
<Toast.Description className={styles.Description}>{toast.description}</Toast.Description>
<Toast.CloseTrigger className={styles.CloseTrigger}>
<XIcon />
</Toast.CloseTrigger>
</Toast.Root>
)}
</Toaster>
</Portal>
</div>
)
}
유형 (Types)
적절한 스타일로 다양한 유형의 토스트(success, error, warning, info)를 만들 수 있습니다. 예를 들어, 성공 토스트를 만들려면 다음과 같이 할 수 있습니다:
toaster.success({
title: 'Success!',
description: 'Your changes have been saved.',
})
import { Portal } from '@ark-ui/react/portal'
import { Toast, Toaster, createToaster } from '@ark-ui/react/toast'
import { CircleAlertIcon, TriangleAlertIcon, CircleCheckIcon, InfoIcon, XIcon } from 'lucide-react'
import button from 'styles/button.module.css'
import styles from 'styles/toast.module.css'
const toaster = createToaster({
overlap: true,
placement: 'bottom-end',
gap: 16,
})
const iconMap = {
success: CircleCheckIcon,
error: CircleAlertIcon,
warning: TriangleAlertIcon,
info: InfoIcon,
}
export const Types = () => {
return (
<div>
<div style={{ display: 'flex', gap: '12px', flexWrap: 'wrap' }}>
<button
type="button"
className={button.Root}
onClick={() =>
toaster.success({ title: 'Changes saved', description: 'Your profile has been updated successfully.' })
}
>
Success
</button>
<button
type="button"
className={button.Root}
onClick={() =>
toaster.error({ title: 'Upload failed', description: 'There was an error uploading your file.' })
}
>
Error
</button>
<button
type="button"
className={button.Root}
onClick={() =>
toaster.warning({ title: 'Low storage', description: 'You have less than 10% storage remaining.' })
}
>
Warning
</button>
<button
type="button"
className={button.Root}
onClick={() =>
toaster.info({ title: 'Update available', description: 'A new version of the app is ready to install.' })
}
>
Info
</button>
</div>
<Portal>
<Toaster toaster={toaster}>
{(toast) => {
const ToastIcon = toast.type ? iconMap[toast.type as keyof typeof iconMap] : undefined
return (
<Toast.Root key={toast.id} className={styles.Root}>
<Toast.Title className={styles.Title}>
{ToastIcon && <ToastIcon className={styles.Indicator} />}
{toast.title}
</Toast.Title>
<Toast.Description className={styles.Description}>{toast.description}</Toast.Description>
<Toast.CloseTrigger className={styles.CloseTrigger}>
<XIcon />
</Toast.CloseTrigger>
</Toast.Root>
)
}}
</Toaster>
</Portal>
</div>
)
}
프로미스 (Promise)
toaster.promise()를 사용하면 비동기 작업의 여러 상태를 자동으로 처리할 수 있습니다. 프로미스의 success, error, loading 상태에 대한 옵션을 제공하며, 프로미스가 resolve되거나 reject될 때 토스트를 자동으로 업데이트합니다.
import { Portal } from '@ark-ui/react/portal'
import { Toast, Toaster, createToaster } from '@ark-ui/react/toast'
import { XIcon, LoaderIcon, CircleCheckIcon, CircleAlertIcon } from 'lucide-react'
import button from 'styles/button.module.css'
import styles from 'styles/toast.module.css'
const toaster = createToaster({
overlap: true,
placement: 'bottom-end',
gap: 16,
})
const uploadFile = () => {
return new Promise<void>((resolve, reject) => {
setTimeout(() => {
Math.random() > 0.5 ? resolve() : reject(new Error('Upload failed'))
}, 2000)
})
}
export const PromiseToast = () => {
const handleUpload = async () => {
toaster.promise(uploadFile, {
loading: {
title: 'Uploading file...',
description: 'Please wait while we upload your document.',
},
success: {
title: 'Upload complete',
description: 'Your file has been uploaded successfully.',
},
error: {
title: 'Upload failed',
description: 'Could not upload the file. Please try again.',
},
})
}
const getIcon = (type: string | undefined) => {
switch (type) {
case 'loading':
return <LoaderIcon className={styles.Indicator} data-type="loading" />
case 'success':
return <CircleCheckIcon className={styles.Indicator} />
case 'error':
return <CircleAlertIcon className={styles.Indicator} />
default:
return null
}
}
return (
<div>
<button type="button" className={button.Root} onClick={handleUpload}>
Upload file
</button>
<Portal>
<Toaster toaster={toaster}>
{(toast) => (
<Toast.Root key={toast.id} className={styles.Root}>
<Toast.Title className={styles.Title}>
{getIcon(toast.type)}
{toast.title}
</Toast.Title>
<Toast.Description className={styles.Description}>{toast.description}</Toast.Description>
<Toast.CloseTrigger className={styles.CloseTrigger}>
<XIcon />
</Toast.CloseTrigger>
</Toast.Root>
)}
</Toaster>
</Portal>
</div>
)
}
업데이트 (Update)
토스트를 업데이트하려면 toast.update 메서드를 사용합니다.
import { Portal } from '@ark-ui/react/portal'
import { Toast, Toaster, createToaster } from '@ark-ui/react/toast'
import { useRef } from 'react'
import button from 'styles/button.module.css'
import styles from 'styles/toast.module.css'
const toaster = createToaster({
placement: 'bottom-end',
overlap: true,
gap: 24,
})
export const Update = () => {
const id = useRef<string>(undefined)
const createToast = () => {
id.current = toaster.create({
title: 'Sending message...',
description: 'Please wait while we deliver your message.',
type: 'loading',
})
}
const updateToast = () => {
if (!id.current) {
return
}
toaster.update(id.current, {
title: 'Message sent',
description: 'Your message has been delivered successfully.',
type: 'success',
})
}
return (
<div className="hstack">
<button type="button" className={button.Root} onClick={createToast}>
Send message
</button>
<button type="button" className={button.Root} onClick={updateToast}>
Mark as sent
</button>
<Portal>
<Toaster toaster={toaster}>
{(toast) => (
<Toast.Root key={toast.id} className={styles.Root}>
<Toast.Title className={styles.Title}>{toast.title}</Toast.Title>
<Toast.Description className={styles.Description}>{toast.description}</Toast.Description>
</Toast.Root>
)}
</Toaster>
</Portal>
</div>
)
}
액션 (Action)
토스트에 액션을 추가하려면 toast.action 속성을 사용합니다.
import { Portal } from '@ark-ui/react/portal'
import { Toast, Toaster, createToaster } from '@ark-ui/react/toast'
import button from 'styles/button.module.css'
import styles from 'styles/toast.module.css'
const toaster = createToaster({
placement: 'bottom-end',
gap: 24,
})
export const Action = () => {
return (
<div>
<button
type="button"
className={button.Root}
onClick={() =>
toaster.create({
title: 'Event has been created',
description: 'We have sent you an email with the event details.',
type: 'info',
action: {
label: 'Undo',
onClick: () => {
console.log('Undo')
},
},
})
}
>
Create event
</button>
<Portal>
<Toaster toaster={toaster}>
{(toast) => (
<Toast.Root key={toast.id} className={styles.Root}>
<Toast.Title className={styles.Title}>{toast.title}</Toast.Title>
<Toast.Description className={styles.Description}>{toast.description}</Toast.Description>
{toast.action && (
<Toast.ActionTrigger className={styles.ActionTrigger}>{toast.action?.label}</Toast.ActionTrigger>
)}
</Toast.Root>
)}
</Toaster>
</Portal>
</div>
)
}
지속 시간 (Duration)
토스트가 표시되는 시간을 밀리초 단위의 사용자 지정 duration으로 제어하거나, Infinity를 사용하여 수동으로 닫을 때까지 계속 표시할 수 있습니다.
import { Portal } from '@ark-ui/react/portal'
import { Toast, Toaster, createToaster } from '@ark-ui/react/toast'
import { XIcon, ClockIcon } from 'lucide-react'
import button from 'styles/button.module.css'
import styles from 'styles/toast.module.css'
const toaster = createToaster({
overlap: true,
placement: 'bottom-end',
gap: 16,
})
const durations = [
{ label: '1s', value: 1000 },
{ label: '3s', value: 3000 },
{ label: '5s', value: 5000 },
{ label: '∞', value: Infinity },
]
export const Duration = () => {
return (
<div>
<div style={{ display: 'flex', flexWrap: 'wrap', gap: '8px' }}>
{durations.map((duration) => (
<button
key={duration.label}
type="button"
className={button.Root}
onClick={() =>
toaster.create({
title: 'Reminder set',
description: `This notification will ${
duration.value === Infinity ? 'stay until dismissed' : `disappear in ${duration.label}`
}.`,
type: 'info',
duration: duration.value,
})
}
>
{duration.label}
</button>
))}
</div>
<Portal>
<Toaster toaster={toaster}>
{(toast) => (
<Toast.Root key={toast.id} className={styles.Root}>
<Toast.Title className={styles.Title}>
<ClockIcon className={styles.Indicator} />
{toast.title}
</Toast.Title>
<Toast.Description className={styles.Description}>{toast.description}</Toast.Description>
<Toast.CloseTrigger className={styles.CloseTrigger}>
<XIcon />
</Toast.CloseTrigger>
</Toast.Root>
)}
</Toaster>
</Portal>
</div>
)
}
최대 표시 수 (Max Visible)
createToaster 함수에 max prop을 설정하여 한 번에 렌더링할 수 있는 최대 토스트 수를 정의합니다. 추가 토스트는 대기열에 쌓였다가 토스트가 닫히면 렌더링됩니다.
import { Portal } from '@ark-ui/react/portal'
import { Toast, Toaster, createToaster } from '@ark-ui/react/toast'
import { XIcon, InfoIcon } from 'lucide-react'
import button from 'styles/button.module.css'
import styles from 'styles/toast.module.css'
const toaster = createToaster({
max: 3,
overlap: true,
placement: 'bottom-end',
gap: 16,
})
export const MaxToasts = () => {
return (
<div>
<div style={{ display: 'flex', flexWrap: 'wrap', gap: '8px' }}>
<button
type="button"
className={button.Root}
onClick={() =>
toaster.create({
title: 'New notification',
description: 'You have a new message in your inbox.',
type: 'info',
})
}
>
Add notification
</button>
<button
type="button"
className={button.Root}
onClick={() => {
const messages = [
'John liked your post',
'Sarah commented on your photo',
'New follower: @designpro',
'Your post was shared 10 times',
'Meeting reminder in 15 minutes',
]
messages.forEach((msg) => {
toaster.create({
title: 'Notification',
description: msg,
type: 'info',
})
})
}}
>
Add 5 notifications
</button>
</div>
<Portal>
<Toaster toaster={toaster}>
{(toast) => (
<Toast.Root key={toast.id} className={styles.Root}>
<InfoIcon className={styles.Indicator} />
<div style={{ flex: 1 }}>
<Toast.Title className={styles.Title}>{toast.title}</Toast.Title>
<Toast.Description className={styles.Description}>{toast.description}</Toast.Description>
</div>
<Toast.CloseTrigger className={styles.CloseTrigger}>
<XIcon />
</Toast.CloseTrigger>
</Toast.Root>
)}
</Toaster>
</Portal>
</div>
)
}
위치 (Placement)
createToaster의 placement 옵션으로 토스트가 화면에 나타나는 위치를 구성할 수 있습니다. 옵션에는 top-start, top-end, bottom-start, bottom-end 등이 있습니다.
import { Portal } from '@ark-ui/react/portal'
import { Toast, Toaster, createToaster } from '@ark-ui/react/toast'
import { XIcon } from 'lucide-react'
import button from 'styles/button.module.css'
import styles from 'styles/toast.module.css'
const toaster = createToaster({
placement: 'top-end',
overlap: true,
gap: 16,
})
export const Placement = () => {
return (
<div>
<button
type="button"
className={button.Root}
onClick={() =>
toaster.create({
title: 'Notification',
description: 'This toast appears at the top-right corner.',
type: 'info',
})
}
>
Show toast (top-end)
</button>
<Portal>
<Toaster toaster={toaster}>
{(toast) => (
<Toast.Root key={toast.id} className={styles.Root}>
<Toast.Title className={styles.Title}>{toast.title}</Toast.Title>
<Toast.Description className={styles.Description}>{toast.description}</Toast.Description>
<Toast.CloseTrigger className={styles.CloseTrigger}>
<XIcon />
</Toast.CloseTrigger>
</Toast.Root>
)}
</Toaster>
</Portal>
</div>
)
}
가이드 (Guides)
효과 안에서의 토스트 (Toast in Effects)
React 효과(useEffect, useLayoutEffect, 또는 렌더 중 트리거되는 이벤트 핸들러) 내부에서 토스트를 만들면 "flushSync" 경고가 발생할 수 있습니다. 이를 피하려면 토스트 호출을 queueMicrotask로 감싸세요:
import { useEffect } from 'react'
export const EffectToast = () => {
useEffect(() => {
// ❌ This may cause flushSync warnings
// toaster.create({ title: 'Effect triggered!' })
// ✅ Wrap in queueMicrotask to avoid warnings
queueMicrotask(() => {
toaster.create({
title: 'Effect triggered!',
description: 'This toast was called safely from an effect',
type: 'success',
})
})
}, [])
return <div>Component content</div>
}
이렇게 하면 토스트 생성이 현재 실행 컨텍스트 이후로 지연되어 React의 동시(concurrent) 렌더링 경고를 방지합니다.
스타일링 (Styling)
토스트가 올바르게 작동하려면 최소한의 스타일링이 필요합니다.
토스트 루트 (Toast root)
토스트 루트에는 런타임에 다음 CSS 속성이 할당됩니다:
--x- x 위치--y- y 위치--scale- 배율(scale)--z-index- z-index--height- 높이--opacity- 불투명도--gap- 토스트 사이의 간격
[data-scope='toast'][data-part='root'] {
translate: var(--x) var(--y);
scale: var(--scale);
z-index: var(--z-index);
height: var(--height);
opacity: var(--opacity);
will-change: translate, opacity, scale;
transition:
translate 400ms,
scale 400ms,
opacity 400ms,
height 400ms,
box-shadow 200ms;
transition-timing-function: cubic-bezier(0.21, 1.02, 0.73, 1);
&[data-state='closed'] {
transition:
translate 400ms,
scale 400ms,
opacity 200ms;
transition-timing-function: cubic-bezier(0.06, 0.71, 0.55, 1);
}
}
유형에 따른 스타일링 (Styling based on type)
data-type 속성을 기반으로 스타일을 지정할 수도 있습니다.
[data-scope='toast'][data-part='root'] {
&[data-type='error'] {
background: red;
color: white;
}
&[data-type='info'] {
background: blue;
color: white;
}
&[data-type='warning'] {
background: orange;
}
&[data-type='success'] {
background: green;
color: white;
}
}
모바일 고려 사항 (Mobile considerations)
매우 흔한 사용 사례는 모바일에서 토스트 너비를 조정하여 화면 전체 너비에 걸치게 하는 것입니다.
@media (max-width: 640px) {
[data-scope='toast'][data-part='group'] {
width: 100%;
}
[data-scope='toast'][data-part='root'] {
inset-inline: 0;
width: calc(100% - var(--gap) * 2);
}
}
API 참조 (API Reference)
Props
Root
Props
asChild
Type: boolean
Required: false
Default Value: undefined
Description: 제공된 자식 요소를 기본 렌더링 요소로 사용하며, 해당 요소의 props와 동작을 결합합니다.
데이터 속성 (Data Attributes)
data-scope: toast
data-part: root
data-state: "open" | "closed"
data-type: 항목의 유형입니다.
data-placement: 토스트의 위치입니다.
data-align:
data-side: 토스트가 위치하는 트리거의 측면입니다.
data-mounted: 마운트되었을 때 표시됩니다.
data-paused: 일시 중지되었을 때 표시됩니다.
data-first:
data-sibling:
data-stack:
data-overlap: 중첩되었을 때 표시됩니다.
ActionTrigger
Props
asChild
Type: boolean
Required: false
Default Value: undefined
Description: 제공된 자식 요소를 기본 렌더링 요소로 사용하며, 해당 요소의 props와 동작을 결합합니다.
CloseTrigger
Props
asChild
Type: boolean
Required: false
Default Value: undefined
Description: 제공된 자식 요소를 기본 렌더링 요소로 사용하며, 해당 요소의 props와 동작을 결합합니다.
Description
Props
asChild
Type: boolean
Required: false
Default Value: undefined
Description: 제공된 자식 요소를 기본 렌더링 요소로 사용하며, 해당 요소의 props와 동작을 결합합니다.
Store
Props
duration
Type: number
Required: false
Default Value: undefined
Description: 토스트의 지속 시간입니다.
기본적으로는 토스트의 유형에 따라 결정됩니다.
gap
Type: number
Required: false
Default Value: 16
Description: 토스트 사이의 간격입니다.
hotkey
Type: string[]
Required: false
Default Value: '["altKey", "KeyT"]'
Description: 토스트 그룹으로 포커스를 이동시키는 단축키입니다.
max
Type: number
Required: false
Default Value: 24
Description: 최대 토스트 수입니다. 토스트 수가 이 한도를 초과하면 새 토스트는 대기열에 쌓입니다.
offsets
Type: string | Record<'top' | 'bottom' | 'left' | 'right', string>
Required: false
Default Value: "1rem"
Description: 뷰포트의 안전 영역 가장자리로부터의 오프셋입니다.
overlap
Type: boolean
Required: false
Default Value: undefined
Description: 토스트를 중첩할지 여부입니다.
pauseOnPageIdle
Type: boolean
Required: false
Default Value: false
Description: 사용자가 브라우저 탭을 떠날 때 토스트를 일시 중지할지 여부입니다.
placement
Type: Placement
Required: false
Default Value: "bottom"
Description: 토스트의 위치입니다.
removeDelay
Type: number
Required: false
Default Value: 200
Description: 토스트가 제거되기 전에 유지되는 시간입니다.
퇴장(exit) 전환에 유용합니다.
Title
Props
asChild
Type: boolean
Required: false
Default Value: undefined
Description: 제공된 자식 요소를 기본 렌더링 요소로 사용하며, 해당 요소의 props와 동작을 결합합니다.
Toaster
Props
toaster
Type: CreateToasterReturn<any>
Required: true
Default Value: undefined
Description: undefined
asChild
Type: boolean
Required: false
Default Value: undefined
Description: 제공된 자식 요소를 기본 렌더링 요소로 사용하며, 해당 요소의 props와 동작을 결합합니다.
dir
Type: 'ltr' | 'rtl'
Required: false
Default Value: "ltr"
Description: 문서의 텍스트/쓰기 방향입니다.
getRootNode
Type: () => ShadowRoot | Node | Document
Required: false
Default Value: undefined
Description: 사용자 지정 환경에서 문서를 올바르게 resolve하기 위한 루트 노드입니다. 예: Iframes, Electron.
Context
API:
| Property | Type | Description |
|---|---|---|
getCount |
() => number |
토스트의 총 개수입니다. |
getToasts |
() => ToastProps[] |
토스트 목록입니다. |
subscribe |
(callback: (toasts: Options<O>[]) => void) => VoidFunction |
토스트 그룹을 구독합니다. |