리액트 프로젝트에서 토스트 메시지 띄우기
해당 기능을 제공하는 라이브러리를 사용하면 간단하게 구현할 수 있다.
react-toastify 라이브러리 설치하기
npm 혹은 yarn을 통해 라이브러리를 프로젝트 내에 설치한다.
$ npm install --save react-toastify
$ yarn add react-toastify
ToastProvider 컴포넌트 만들기
Next.js 의 app router를 사용하고 있다면 'use client'를 통해서 클라이언트 측에서 실행되도록 한다.
'use client'
import { ToastContainer } from 'react-toastify'
import 'react-toastify/dist/ReactToastify.min.css'
const ToastProvider = () => {
return <ToastContainer autoClose={2000} />
}
export default ToastProvider
Layout 컴포넌트 설정하기
app 폴더의 layout.jsx(tsx) 파일에 ToastProvider 컴포넌트를 임포트하여 body 태그 안에 넣어준다.
import ToastProvider from '@/components/toastProvider/ToastProvider'
export default function RootLayout({ children }) {
return (
<html lang='en'>
<body>
<ToastProvider />
{children}
</body>
</html>
)
}
toast 사용하기
toast를 임포트해서 메서드를 통해 사용한다.
success, error, warn, info 4가지의 타입으로 지정할 수 있다.
import { toast } from 'react-toastify'
function toastSuccess(message) {
toast.info(message)
}
기타 사항 확인하기
아래 주소에서 상세한 사용법을 확인할 수 있다.
https://fkhadra.github.io/react-toastify/introduction
React-toastify | React-Toastify
Financial Contributors on Open Collective
fkhadra.github.io
'웹' 카테고리의 다른 글
Next Image 사용할 때 주의할 점 (0) | 2024.01.17 |
---|---|
Redux Toolkit 으로 상태 관리하기 (0) | 2024.01.17 |
[Svelte] 프로젝트 생성하기 (0) | 2023.06.21 |
자바스크립트 번들러 (0) | 2023.06.15 |
브라우저에 토큰 저장하기 (0) | 2023.06.15 |