Programming/React
[React.js] react-toastify 라이브러리
adastra
2024. 9. 10. 19:52
728x90
728x90
react-toastify 라이브러리
들어가며
- 간단하게 토스트(Toast) 메시지를 띄워야할 때 @react-toastify@ 라이브러리를 사용할 수 있다.
- @react-toastify@ 라이브러리의 사용법을 간단하게 정리해본다.

react-toastify 라이브러리
개념
- 리액트 애플리케이션에서 사용자에게 알림을 제공하는 토스트 메시지(Notification)를 쉽게 구현할 수 있게 해주는 라이브러리
- 이 라이브러리를 사용하여 다양한 스타일과 애니메이션 효과로 간단하게 알림을 띄울 수 있다.
- 기본적으로 설정이 간편하며, 다양한 사용자 정의 옵션을 제공하여 알림을 원하는 대로 커스터마이징할 수 있다.

라이브러리 설치
$ npm install react-toastify # yarn add react-toastify
사용법
① main.jsx(index.js) 파일에서 css 파일 불러오기
- Vite를 이용하여 프로젝트를 생성하였을 경우, @main.jsx@ 파일에, React-Create-App을 이용하여 프로젝트를 생성하였을 경우 @index.js@ 파일에 아래와 같은 @css@ 파일을 import 한다.
import 'react-toastify/dist/ReactToastify.css';
./src/main.jsx (index.js)
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import './index.css';
import 'react-toastify/dist/ReactToastify.css'; // 추가
ReactDOM.createRoot(document.getElementById('root')).render(
<React.StrictMode>
<App />
</React.StrictMode>
);
② App.jsx 파일에서 @ToastContainer@ 생성하기
- @App.jsx@ (또는 @App.js@) 파일에서 @<ToastContainer />@ 컴포넌트를 import 하여 추가해준다.
./src/App.jsx (App.js)
import { ToastContainer } from 'react-toastify';
const App = () => {
// ...
return (
<main>
<Form addColor={addColor} />
<ColorList colors={colors} />
<ToastContainer position="top-center" /> {/* ToastContainer 추가 */}
</main>
);
};
export default App;
③ 원하는 컴포넌트에서 사용하기
- 이제 원하는 컴포넌트에서 @toast@ 메서드를 불러와 사용하면 된다.
import { toast } from 'react-toastify'; // toast 메서드 import
const SingleColor = ({ index, color }) => {
const { hex, weight } = color;
const saveToClipboard = async () => {
if (navigator.clipboard) {
try {
await navigator.clipboard.writeText(`#${hex}`);
toast.success('Color copied to clipboard.'); // 성공 toast 메시지 띄우기
} catch (error) {
toast.error('Failed to copy color to clipboard.'); // 에러 toast 메시지 띄우기
}
} else {
toast.error('Clipboard access not available.'); // 에러 toast 메시지 띄우기
}
};
return (
<article
className={index > 10 ? 'color color-light' : 'color'}
style={{ background: `#${hex}` }}
onClick={saveToClipboard}
>
<p className="percent-value">{weight}%</p>
<p className="color-value">#{hex}</p>
</article>
);
};
export default SingleColor;
공식 문서
- 더 자세한 사용법은 아래의 공식 문서를 참고한다.
React-toastify | React-Toastify
Financial Contributors on Open Collective
fkhadra.github.io
참고 사이트
react-toastify
React notification made easy. Latest version: 10.0.5, last published: 6 months ago. Start using react-toastify in your project by running `npm i react-toastify`. There are 2573 other projects in the npm registry using react-toastify.
www.npmjs.com
728x90
728x90