Studying/React

리액트 공부하기 - toastify 라이브러리 초보 설명

creamymood 2025. 5. 28. 17:16

조교님이나 동기분들하고 대화하다보면 좋은 꿀 정보를 많이 얻는다 !

그 중 하나 toastify.

기존 alert 대신에 사용해볼 수 있어서 흥미로워 보였다 ! 라이브러리라 사용도 간편할 것 같았다 🐰🤍


 

 

 react-toastify란?

사용자에게 빠르고 가볍게 피드백(알림)을 줄 수 있는 Toast UI 라이브러리


"Toast"란?

웹/앱에서 화면 한쪽에 짧게 뜨는 알림 메시지

  • 로그인 성공 → "로그인에 성공했습니다!"
  • 장바구니 추가 → "상품이 장바구니에 담겼어요."

공식 문서에서 안내해주는 설치 방법과 간단한 사용 예시

Installation

$ npm install --save react-toastify
$ yarn add react-toastify
  import React from 'react';

  import { ToastContainer, toast } from 'react-toastify';
  
  function App(){
    const notify = () => toast("Wow so easy!");

    return (
      <div>
        <button onClick={notify}>Notify!</button>
        <ToastContainer />
      </div>
    );
  }

 

 

 

React-toastify | React-Toastify

Financial Contributors on Open Collective

fkhadra.github.io

해당 사이트는, 사용방법 등 다양하게 안내되어 있다.

 

사이트에서 이런 식으로 쉽게 예시를 직접 볼 수 있고, 커스터마이징 할 수 있다.

 

 


사용방법

1) 커스텀 컴포넌트 없이,  당장 실행 시켜볼 수 있는 초간단 코드 

(공식으로 제공하는 간단한 helper 함수). 

 

toast.success, toast.error, toast.info, toast.warn 등은
toast() 함수의 shortcut 버전으로 초 간단히~~ 컨테이너만 넣어주고, 사용 원하는 컴포넌트에서 바로 이렇게 사용하면

toast("일반 메시지"); // 기본 Toast
toast.success("성공 메시지");
toast.error("에러 메시지");
toast.info("정보 메시지");
toast.warn("경고 메시지");

 

원하는 위치나 지속시간도 지정 가능하다.

toast.success("저장 완료!", {
  position: "bottom-right",
  autoClose: 3000,
});

 


 

 

2) 유틸 파일을 만들어서, 원하는 대로 사용

: toastUtil.js 이런 식으로 만들어서

import { toast } from 'react-toastify';

export const notifySuccess = (message) => toast.success(message);
export const notifyError = (message) => toast.error(message);
export const notifyInfo = (message) => toast.info(message);

 

. 기존 alert("문구") → toast 함수로 교체

import { notifySuccess } from './toastUtil';

// 예시:
notifySuccess("성공적으로 저장되었습니다!");

주의 !

1. <ToastContainer />는 반드시 넣어야 한다.


toast() 함수는 단순히 "띄워줘!" 하고 명령만 내릴 뿐이고,
<ToastContainer />가 실제로 그걸 브라우저에 표시하는 역할

 

보통 이런 식으로 넣는다.

function App() {
  return (
    <>
      <MyComponent />
      <ToastContainer />
    </>
  );
}
  • 보통은 앱의 루트 컴포넌트에 한 번만 넣음
  • 여러 개 넣으면 알림이 중복될 수 있다

 

 2. CSS import도 절대 기억하기

 

react-toastify는 기본 스타일이 있어야 알림이 제대로 보인다.

import 'react-toastify/dist/ReactToastify.css';

Toastify 추가 주의사항 & 유용한 팁

더보기

1. 중복 알림 방지하려면 toast.isActive() 사용

  • 같은 메시지가 계속 떠서 사용자에게 불편함을 줄 수 있다
  • 이럴 땐 중복 방지를 위해 ID를 설정하거나, toast.isActive()를 사용 하기
const toastId = 'saving';

if (!toast.isActive(toastId)) {
  toast.success('저장되었습니다!', { toastId });
}

 

 

2.  자동 닫힘 시간 설정 (autoClose)

toast('3초 후 닫힘!', {
  autoClose: 3000, // 3초
});
  • 기본값은 5초 (5000ms)
  • false로 하면 수동으로만 닫을 수 있음

3. 위치 조절 (position)

<ToastContainer position="top-center" />
  • 기본값: top-right
  • 다른 값들:
    top-left, top-center, bottom-left, bottom-right, bottom-center

4.  스타일 커스터마이징

toast.success('완료!', {
  style: {
    backgroundColor: '#333',
    color: '#fff',
  },
});

또는 ToastContainer에 theme을 지정해도 됌:

<ToastContainer theme="dark" />

 

 

5.  Promise와 함께 쓰기 (toast.promise)

  • API 호출 같은 비동기 처리에서 유용
toast.promise(fetch('/save'), {
  pending: '저장 중...',
  success: '저장 완료!',
  error: '저장 실패 😢',
});

 

6. 한 번에 모든 Toast 지우기

toast.dismiss(); // 모든 토스트 닫기

또는 특정 ID만 닫기:

toast.dismiss(toastId);

 

 


리액트 toastify 공식 문서 

 

react-toastify

React notification made easy. Latest version: 11.0.5, last published: 3 months ago. Start using react-toastify in your project by running `npm i react-toastify`. There are 2977 other projects in the npm registry using react-toastify.

www.npmjs.com