FrontEnd/React

[React] 웹 에서 Toast를 띄워보기 (react-toastify)

kangminhyuk1111 2024. 2. 14. 09:05

Android Toast

안드로이드는 개발환경에서 Toast 라는 작은 메세지 박스를 자체적으로 구현이 가능합니다.

 

하지만 웹 어플리케이션에서는 custom 을 해주거나 별도로 라이브러리를 사용해야합니다.

 

사용하려면?

react에서 지원되는 react-toastify라는 라이브러리를 통해 쉽게 toast 메세지 박스를 구현가능합니다.

 

react-toastify 사용법

이 글은 react(nextjs) 를 기반으로 작성되었습니다.

 

공식문서

https://www.npmjs.com/package/react-toastify

 

react-toastify

React notification made easy. Latest version: 10.0.4, last published: 24 days ago. Start using react-toastify in your project by running `npm i react-toastify`. There are 2206 other projects in the npm registry using react-toastify.

www.npmjs.com

먼저 npm혹은 yarn으로 패키지를 install 해줍니다.

$ npm install --save react-toastify
$ yarn add react-toastify

 

이후 설치가 완료되었다면 react app 에 적용시킵니다.

 

example code

  import React from 'react';

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

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

 

위 예제 코드에서는 버튼 클릭시 toast창을 띄우도록 되어있는 것 같습니다.

그리고 ToastContainer를 반드시 넣어줘야 하며

css import도 빠지면 안됩니다.

 

일단 저는 전역적으로 ToastContainer를 넣어주어서 아래 하위 컴포넌트들이 모두 사용할 수 있도록 하겠습니다.

export default function RootLayout({children}: { children: React.ReactNode }) {
    return (
        <html lang={"ko"}>
        <body className={`${inter.className}`}>
        <RQProvider>
            <ToastContainer
                position="top-center"
                limit={1}
                closeButton={false}
                autoClose={4000}
                hideProgressBar
            />
            {children}
        </RQProvider>
        </body>
        </html>
    )
}

위 코드는 nextjs입니다. next를 모르신다면 이해하기 편하도록

 

위는 App.js 라고 생각하시면 됩니다.

 

각각의 속성이 있는데 해석하자면

 

position은 toast창의 위치

 

limit은 최대 표현 개수

 

closeButton은 버튼클릭 x 표시가 존재하는지 여부

 

autoClose는 자동 종료입니다. 1000 = 1 second

 

hideProgressBar는 autoClose초에 맞춰서 줄어드는 바라고 생각하시면 됩니다

 

더 많은 속성들은 

https://fkhadra.github.io/react-toastify/introduction/

 

React-toastify | React-Toastify

Financial Contributors on Open Collective

fkhadra.github.io

아래 페이지에서 적용하여 사용가능 하며 적용시 우측 코드에 적용된 코드들이 나옵니다. 복붙해서 사용하시면 됩니다.

 

이후 적용한 모습을 보여드리겠습니다.

이런식으로 내부 메세지 커스텀이 가능합니다.

저는 서버에서 돌려주는 에러메세지를 사용해서 띄웠습니다.

export const customErrToast = (str: string) => {
    return toast.error(str, {
        position: "top-center",
        autoClose: 3000,
        hideProgressBar: false,
        closeOnClick: true,
        pauseOnHover: true,
        draggable: true,
        progress: undefined,
        theme: "dark",
        transition: Slide,
    });
}

 

외부 파일에 따로 선언을 먼저해놓고

 

catch (err:any) {
            customErrToast(err.response.data.message)
        }

 

try catch에서 error 를 반환할때 에러메세지를 toast message에 넣어주는 방식으로 구현했습니다.

 

공식문서 설명이 잘 되어 있으니 바탕으로 한번 찾아보고 만들어보시면 좋을 것 같습니다.

반응형