🔥React 뽀개기
Toast 공통 컴포넌트 만들기 (feat.react-toastify)
짱돌보리
2024. 8. 8. 15:32
728x90
목표))
- react-toastify로 토스트 구현하기
- 공통컴포넌트로 만들기 (성공, 실패, 에러, 멘트 프롭으로 받기)
https://fkhadra.github.io/react-toastify/icons
Icons | React-Toastify
Built-in icons
fkhadra.github.io
error)
react-toastify의 타입스크립트 사용 시, position 속성이 string 타입으로 정의되어 있어서 발생하는 오류다. position 속성은 ToastPosition 타입으로 설정해야 한다.
import React from 'react';
import { ToastContainer, ToastPosition, toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
const option = {
position: 'top-center' as ToastPosition,
autoClose: 1000,
hideProgressBar: true,
closeOnClick: true,
pauseOnHover: true,
draggable: true,
};
export const notify = (type: 'success' | 'error' | 'info' | 'warning', message: string) => {
switch (type) {
case 'success':
toast.success(message, option);
break;
case 'error':
toast.error(message, option);
break;
case 'info':
toast.info(message, option);
break;
case 'warning':
toast.warn(message, option);
break;
default:
break;
}
};
export default function Toast() {
return <ToastContainer {...option} />;
}
export default function index() {
const handleSuccessToast = () => {
notify('success', 'success');
};
const handleErrorToast = () => {
notify('error', 'error');
};
const handleInfoToast = () => {
notify('info', 'info');
};
const handleWarningToast = () => {
notify('warning', 'warning');
};
return (
<div className="flex flex-col gap-10">
<button onClick={handleSuccessToast} className="border">
success 토스트 알림
</button>
<button onClick={handleErrorToast} className="border">
error 토스트 알림
</button>
<button onClick={handleInfoToast} className="border">
info 토스트 알림
</button>
<button onClick={handleWarningToast} className="border">
warning 토스트 알림
</button>
</div>
</div>
);
}