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

토스트 (Toast)

원문 보기 위키 갱신

Toast는 화면 상단이나 하단에 나타나는 임시 알림 메시지 컴포넌트예요. useToast Hook을 통해 간단한 문자열부터 완전한 커스텀 컴포넌트까지 세 가지 패턴으로 토스트를 표시할 수 있고, 글로벌 설정으로 전체 동작을 일관되게 제어한답니다. 이 문서에서는 세 가지 사용 패턴부터 글로벌 설정, API까지 하나씩 살펴볼게요.

출처: 문서

본문

Import

import { Toast, useToast } from 'heroui-native';

Anatomy

<Toast>
  <Toast.Title>...</Toast.Title>
  <Toast.Description>...</Toast.Description>
  <Toast.Action>...</Toast.Action>
  <Toast.Close />
</Toast>
  • Toast: 알림 메시지를 표시하는 메인 컨테이너예요. 위치 지정, 애니메이션, 스와이프 제스처를 처리해요.
  • Toast.Title: 토스트 알림의 제목 텍스트예요. 상위 Toast 컨텍스트에서 변형 스타일을 상속해요.
  • Toast.Description: 제목 아래에 표시되는 설명 텍스트 콘텐츠예요.
  • Toast.Action: 토스트 안의 액션 버튼이에요. 버튼 변형은 토스트 변형에 따라 자동으로 결정되지만 덮어쓸 수 있어요.
  • Toast.Close: 토스트를 닫는 버튼이에요. 아이콘 전용 버튼으로 렌더링되며, 누르면 hide를 호출해요.

Usage

Usage Pattern 1: Simple String

간단한 문자열 메시지로 토스트를 표시해요.

const { toast } = useToast();

toast.show('This is a toast message');

Usage Pattern 2: Config Object

설정 객체를 사용해 라벨, 설명, 변형, 액션 버튼이 있는 토스트를 표시해요.

const { toast } = useToast();

toast.show({
  variant: 'success',
  label: 'You have upgraded your plan',
  description: 'You can continue using HeroUI Chat',
  icon: <Icon name="check" />,
  actionLabel: 'Close',
  onActionPress: ({ hide }) => hide(),
});

Usage Pattern 3: Custom Component

스타일과 레이아웃을 완전히 제어하기 위해 완전한 커스텀 컴포넌트로 토스트를 표시해요.

const { toast } = useToast();

toast.show({
  component: (props) => (
    <Toast variant="accent" placement="top" {...props}>
      <Toast.Title>Custom Toast</Toast.Title>
      <Toast.Description>This is a custom toast component</Toast.Description>
      <Toast.Close />
    </Toast>
  ),
});

참고: 토스트 아이템은 성능을 위해 메모이즈(memoize)돼요. 커스텀 토스트 컴포넌트에 외부 상태(예: 로딩 상태)를 전달해도 자동으로 갱신되지 않아요. 대신 React Context, 상태 관리 라이브러리, ref 같은 공유 상태 기법을 사용해 상태 갱신이 토스트 컴포넌트로 전파되도록 해야 해요.

Disabling All Animations

"disable-all"을 사용하면 자식을 포함한 모든 애니메이션을 비활성화할 수 있어요. 이 값은 Toast.Action의 Button 같은 모든 하위 컴포넌트로 전파돼요.

const { toast } = useToast();

toast.show({
  variant: 'success',
  label: 'Operation completed',
  description: 'All animations are disabled',
  animation: 'disable-all',
});

또는 커스텀 컴포넌트로:

const { toast } = useToast();

toast.show({
  component: (props) => (
    <Toast variant="accent" animation="disable-all" {...props}>
      <Toast.Title>No animations</Toast.Title>
      <Toast.Description>
        This toast has all animations disabled
      </Toast.Description>
      <Toast.Action>Action</Toast.Action>
    </Toast>
  ),
});

Example

import { Button, Toast, useToast, useThemeColor } from 'heroui-native';
import { View } from 'react-native';

export default function ToastExample() {
  const { toast } = useToast();
  const themeColorForeground = useThemeColor('foreground');

  return (
    <View className="gap-4 p-4">
      <Button
        onPress={() =>
          toast.show({
            variant: 'success',
            label: 'You have upgraded your plan',
            description: 'You can continue using HeroUI Chat',
            actionLabel: 'Close',
            onActionPress: ({ hide }) => hide(),
          })
        }
      >
        Show Success Toast
      </Button>

      <Button
        onPress={() =>
          toast.show({
            component: (props) => (
              <Toast variant="accent" {...props}>
                <Toast.Title>Custom Toast</Toast.Title>
                <Toast.Description>
                  This uses a custom component
                </Toast.Description>
                <Toast.Action onPress={() => props.hide()}>Undo</Toast.Action>
                <Toast.Close className="absolute top-0 right-0" />
              </Toast>
            ),
          })
        }
      >
        Show Custom Toast
      </Button>
    </View>
  );
}

더 많은 예시는 GitHub 저장소에서 찾아볼 수 있어요.

Global Configuration

HeroUINativeProvider의 config prop을 사용해 토스트 동작을 전역으로 설정할 수 있어요. 글로벌 설정은 로컬에서 덮어쓰지 않는 한 모든 토스트의 기본값으로 동작해요.

참고: 완전한 provider 설정 옵션은 Provider 문서를 참고하세요.

Insets

Insets는 토스트의 측면이 화면 가장자리에서 떨어진 거리를 제어해요. Insets는 safe area insets에 더해져요. 모든 토스트가 화면 가장자리에서 20px의 측면 거리를 갖게 하려면 insets를 설정하세요.

<HeroUINativeProvider
  config={{
    toast: {
      insets: {
        top: 20,
        bottom: 20,
        left: 20,
        right: 20,
      },
    },
  }}
>
  {children}
</HeroUINativeProvider>

Content Wrapper with KeyboardAvoidingView

토스트 콘텐츠를 KeyboardAvoidingView로 감싸서 키보드가 나타날 때 토스트가 조정되도록 할 수 있어요.

import {
  KeyboardAvoidingView,
  KeyboardProvider,
} from 'react-native-keyboard-controller';
import { HeroUINativeProvider } from 'heroui-native';
import { useCallback } from 'react';

function AppContent() {
  const contentWrapper = useCallback(
    (children: React.ReactNode) => (
      <KeyboardAvoidingView
        pointerEvents="box-none"
        behavior="padding"
        keyboardVerticalOffset={12}
        className="flex-1"
      >
        {children}
      </KeyboardAvoidingView>
    ),
    []
  );

  return (
    <KeyboardProvider>
      <HeroUINativeProvider
        config={{
          toast: {
            contentWrapper,
          },
        }}
      >
        {children}
      </HeroUINativeProvider>
    </KeyboardProvider>
  );
}

Default Props

variant, placement, animation, swipe 동작의 전역 기본값을 설정할 수 있어요.

<HeroUINativeProvider
  config={{
    toast: {
      defaultProps: {
        variant: 'accent',
        placement: 'bottom',
        isSwipeable: false,
      },
    },
  }}
>
  {children}
</HeroUINativeProvider>

API Reference

Toast

prop type default description
variant 'default' | 'accent' | 'success' | 'warning' | 'danger' 'default' 토스트의 시각적 변형
placement 'top' | 'bottom' 'top' 화면에서의 토스트 위치
isSwipeable boolean true 토스트를 스와이프해서 닫거나 고무 효과로 드래그할 수 있는지 여부
animation ToastRootAnimation - 애니메이션 구성
isAnimatedStyleActive boolean true 애니메이션 스타일(react-native-reanimated) 활성 여부
className string - 토스트 컨테이너의 추가 CSS 클래스
...ViewProps ViewProps - 모든 표준 React Native View prop 지원

ToastRootAnimation

Toast 컴포넌트의 애니메이션 구성이에요. 다음을 사용할 수 있어요.

  • false 또는 "disabled": 루트 애니메이션만 비활성화
  • "disable-all": 자식을 포함한 모든 애니메이션 비활성화
  • true 또는 undefined: 기본 애니메이션 사용
  • object: 사용자 정의 애니메이션 구성
prop type default description
state 'disabled' | 'disable-all' | boolean - 속성을 커스터마이즈하는 동안 애니메이션 비활성화
opacity.value [number, number] [1, 0] 토스트가 보이는 스택을 넘어 이동할 때 페이드 효과를 위한 불투명도 보간 값
opacity.timingConfig WithTimingConfig { duration: 300 } 불투명도 전환의 애니메이션 타이밍 구성
translateY.value [number, number] [0, 10] 쌓인 토스트의 피크 효과를 위한 Y 이동 보간 값
translateY.timingConfig WithTimingConfig { duration: 300 } translateY 전환의 애니메이션 타이밍 구성
scale.value [number, number] [1, 0.97] 쌓인 토스트의 깊이 효과를 위한 스케일 보간 값
scale.timingConfig WithTimingConfig { duration: 300 } 스케일 전환의 애니메이션 타이밍 구성
entering.top EntryOrExitLayoutType FadeInUp
.springify()
.withInitialValues({ opacity: 1, transform: [{ translateY: -100 }] })
.mass(3)
상단 배치의 사용자 정의 진입 애니메이션
entering.bottom EntryOrExitLayoutType FadeInDown
.springify()
.withInitialValues({ opacity: 1, transform: [{ translateY: 100 }] })
.mass(3)
하단 배치의 사용자 정의 진입 애니메이션
exiting.top EntryOrExitLayoutType translateY: -100, scale: 0.97, opacity: 0.5를 사용한 키프레임 애니메이션 상단 배치의 사용자 정의 퇴장 애니메이션
exiting.bottom EntryOrExitLayoutType translateY: 100, scale: 0.97, opacity: 0.5를 사용한 키프레임 애니메이션 하단 배치의 사용자 정의 퇴장 애니메이션

Toast.Title

prop type default description
children React.ReactNode - 제목으로 렌더링할 콘텐츠
className string - 추가 CSS 클래스
...TextProps TextProps - 모든 표준 React Native Text prop 지원

Toast.Description

prop type default description
children React.ReactNode - 설명으로 렌더링할 콘텐츠
className string - 추가 CSS 클래스
...TextProps TextProps - 모든 표준 React Native Text prop 지원

Toast.Action

Toast.Action는 Button 컴포넌트의 모든 prop을 확장해요. 버튼 변형은 토스트 변형에 따라 자동으로 결정되지만 덮어쓸 수 있어요.

prop type default description
children React.ReactNode - 액션 버튼 라벨로 렌더링할 콘텐츠
variant ButtonVariant - 버튼 변형. 제공하지 않으면 토스트 변형에서 자동으로 결정
size 'sm' | 'md' | 'lg' 'sm' 액션 버튼의 크기
className string - 추가 CSS 클래스

onPress, isDisabled, 그리고 모든 Button prop을 포함한 상속 prop에 대해서는 Button API Reference를 참고하세요.

Toast.Close

Toast.Close는 Button 컴포넌트의 모든 prop을 확장해요.

prop type default description
children React.ReactNode - 사용자 정의 닫기 아이콘. 기본값은 CloseIcon
iconProps { size?: number; color?: string } - 기본 닫기 아이콘의 props
size 'sm' | 'md' | 'lg' 'sm' 닫기 버튼의 크기
className string - 추가 CSS 클래스
onPress (event: any) => void - 사용자 정의 누름 핸들러. 기본값은 토스트 숨기기

isDisabled와 모든 Button prop을 포함한 상속 prop에 대해서는 Button API Reference를 참고하세요.

ToastProviderProps

HeroUINativeProvider의 config prop을 통해 토스트 동작을 전역으로 설정하기 위한 props예요.

prop type default description
defaultProps ToastGlobalConfig - 모든 토스트의 기본값으로 사용되는 전역 토스트 구성
disableFullWindowOverlay boolean false iOS에서 true면 FullWindowOverlay 대신 View를 사용해요. 요소 인스펙터를 활성화하며, 토스트가 네이티브 모달 위에는 나타나지 않아요
unstable_accessibilityContainerViewIsModal boolean false VoiceOver가 오버레이 창을 모달 컨테이너로 취급할지 제어해요. true면 VoiceOver가 오버레이 안의 요소로 제한돼요. iOS 전용. 불안정: react-native-screens 업데이트에 따라 변경될 수 있어요
insets ToastInsets - 화면 가장자리와의 간격 (safe area insets에 더해짐)
maxVisibleToasts number 3 불투명도가 페이드되기 전에 보이는 최대 토스트 수
contentWrapper (children: React.ReactNode) => React.ReactElement - 토스트 콘텐츠를 감싸는 사용자 정의 래퍼 함수
children React.ReactNode - 렌더링할 children

ToastGlobalConfig

로컬에서 덮어쓰지 않는 한 모든 토스트의 기본값으로 사용되는 전역 토스트 구성이에요.

prop type description
variant 'default' | 'accent' | 'success' | 'warning' | 'danger' 토스트의 시각적 변형
placement 'top' | 'bottom' 화면에서의 토스트 위치
isSwipeable boolean 토스트를 스와이프해서 닫거나 고무 효과로 드래그할 수 있는지 여부
animation ToastRootAnimation 토스트의 애니메이션 구성

ToastInsets

화면 가장자리와의 간격을 위한 insets예요. 값은 safe area insets에 더해져요.

prop type default description
top number - 위쪽 가장자리로부터의 픽셀 간격 (safe area inset에 더해짐). 플랫폼별: iOS = 0, Android = 12
bottom number - 아래쪽 가장자리로부터의 픽셀 간격 (safe area inset에 더해짐). 플랫폼별: iOS = 6, Android = 12
left number - 왼쪽 가장자리로부터의 픽셀 간격 (safe area inset에 더해짐). 기본값: 12
right number - 오른쪽 가장자리로부터의 픽셀 간격 (safe area inset에 더해짐). 기본값: 12

Hooks

useToast

토스트 기능에 접근하는 Hook이에요. ToastProvider(HeroUINativeProvider가 제공) 안에서 사용해야 해요.

return value type description
toast ToastManager show와 hide 메서드가 있는 토스트 관리자
isToastVisible boolean 현재 토스트가 보이는지 여부

ToastManager

method type description
show (options: string | ToastShowOptions) => string 토스트를 표시해요. 표시된 토스트의 ID를 반환해요. 간단한 문자열, 설정 객체, 사용자 정의 컴포넌트의 세 가지 사용 패턴을 지원해요
hide (ids?: string | string[] | 'all') => void 하나 이상의 토스트를 숨겨요. 인자가 없으면 마지막 토스트를, 'all'이면 모든 토스트를, 단일 ID 또는 ID 배열이면 특정 토스트를 숨겨요

ToastShowOptions

토스트를 표시하기 위한 옵션이에요. 기본 스타일의 설정 객체이거나 사용자 정의 컴포넌트일 수 있어요.

설정 객체를 사용할 때 (component 없이):

prop type default description
variant 'default' | 'accent' | 'success' | 'warning' | 'danger' - 토스트의 시각적 변형
placement 'top' | 'bottom' - 화면에서의 토스트 위치
isSwipeable boolean - 토스트를 스와이프해서 닫을 수 있는지 여부
animation ToastRootAnimation | false | "disabled" | "disable-all" - 토스트의 애니메이션 구성
duration number | 'persistent' 4000 자동 숨김 전의 밀리초 지속 시간. 0은 다음 틱에 자동 숨김되고, 'persistent'만 토스트를 화면에 무기한 유지해요
id string - 토스트의 선택적 ID. 제공하지 않으면 생성돼요
label string - 토스트의 라벨 텍스트
description string - 토스트의 설명 텍스트
actionLabel string - 액션 버튼 라벨 텍스트
onActionPress (helpers: { show: (options: string | ToastShowOptions) => string; hide: (ids?: string | string[] | 'all') => void }) => void - 액션 버튼을 눌렀을 때 호출되는 콜백 함수
icon React.ReactNode - 토스트에 표시할 아이콘 요소
onShow () => void - 토스트가 표시될 때 호출되는 콜백 함수
onHide () => void - 토스트가 숨겨질 때 호출되는 콜백 함수

커스텀 컴포넌트를 사용할 때:

prop type default description
id string - 토스트의 선택적 ID. 제공하지 않으면 생성돼요
component (props: ToastComponentProps) => React.ReactElement - 토스트 props를 받아 React 요소를 반환하는 함수
duration number | 'persistent' 4000 자동 숨김 전의 밀리초 지속 시간. 0은 다음 틱에 자동 숨김되고, 'persistent'만 토스트를 화면에 무기한 유지해요
onShow () => void - 토스트가 표시될 때 호출되는 콜백 함수
onHide () => void - 토스트가 숨겨질 때 호출되는 콜백 함수

Special Notes

Element Inspector (iOS)

Toast는 iOS에서 FullWindowOverlay를 사용해요. 개발 중 React Native 요소 인스펙터를 활성화하려면 ToastProvider(HeroUINativeProvider 사용 시 config.toast를 통해)에 disableFullWindowOverlay={true}를 설정하세요. 단점: 비활성화하면 토스트가 네이티브 모달 위에 나타나지 않아요.

더 알아보기 (Learn more)