요즘 공부/새로 알게된 것들

React-toastify를 이용한 토스트 메세지 만들어보자

요즈음 2024. 3. 13. 07:09
320x100

React-toastify

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

기본적으로 우측 상단에 토스트 메세지가 나오도록 만들어져 있다.

Installation

With npm:

npm install --save react-toastify

With yarn:

yarn add react-toastify

The gist

프로젝트 최상단의 toastify css파일과, <ToastContainer/> 컴포넌트를 사용한다.

Remember to render the ToastContainer once in your application tree. If you can't figure out where to put it, rendering it in the application root would be the best bet.
<ToastContainer/> 컴포넌트 는 애플리케이션 루트에 꼭 배치를 해줘야 한다.

import React from 'react';
import { ToastContainer, toast } from 'react-toastify';

import 'react-toastify/dist/ReactToastify.css';
// minified version is also included
// import 'react-toastify/dist/ReactToastify.min.css';

function App(){
  const notify = () => toast("Wow so easy !");

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

Use

사용하고자 하는 곳에 toast() 함수에 필요한 옵션들을 넣어 사용할 수 있다.

import {toast} from 'react-toastify";

const onSubmit = async(e:React.FormEvent<HTMLFormElement>) =>{
  e.preventDefault();
  try{ /* 회원가입에 성공했을떄 */
    toast.success('회원가입에 성공하셨습니다.');
  }catch(error:any){ /* 회원가입에 실패했을때 */
    toast.error(error.code)
  }
}

 

노출되는 화면

반응형