Next.jsアプリでトースト通知を導入したいけど、alert()はダサいし、モーダル出すほどでもない…
そんなときに便利なのが、今回紹介する【react-hot-toast】です。
たった1行で「保存しました」「削除しました」などの通知が表示できて、しかもフォントや色も簡単にカスタマイズ可能!
📌 使用ツール
- Next.js(App Router)
- Tailwind CSS
- react-hot-toast
📌 導入手順
① ライブラリのインストール
npm install react-hot-toast
② app/layout.tsx に <Toaster /> を追加
import { Toaster } from "react-hot-toast";
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="ja">
<body>
{children}
<Toaster
position="top-center"
toastOptions={{
style: {
fontFamily: "var(--font-geist-sans)",
background: "#",
color: "#",
fontSize: "14px",
padding: "12px 16px",
borderRadius: "8px",
boxShadow: "0 2px 6px rgba(0, 0, 0, 0.1)",
},
success: {
iconTheme: {
primary: "#",
secondary: "#",
},
},
error: {
iconTheme: {
primary: "#",
secondary: "#",
},
},
}}
/>
</body>
</html>
);
}
※ フォントは next/font/google で読み込んだCSS変数を活用しています。
③ コンポーネント内で使う
import { toast } from "react-hot-toast";
// 通常の通知
toast.success("保存しました!");
toast.error("エラーが発生しました");
// 削除ボタンでの使用例
const handleDelete = async () => {
const isConfirmed = confirm("本当に削除しますか?");
if (!isConfirmed) return;
toast.loading("削除中...");
const { error } = await supabase
.from("money-savings")
.delete()
.eq("id", id)
.eq("user_id", user.id);
toast.dismiss();
if (error) {
toast.error("削除に失敗しました");
} else {
toast.success("削除しました!");
router.replace("/money-mindful/records/");
}
};
📌 まとめ
• react-hot-toast は超簡単&軽量なトースト通知ライブラリ
• layout.tsx に <Toaster /> を1回追加すれば、全ページで toast() が使える
• CSS変数を使えばフォントや色もアプリ全体と統一できる
alert() や window.confirm() に頼らず、
もっと自然で使いやすい通知UIを取り入れてみましょう。
シンプルなのにしっかり伝わる、そんなトースト通知が欲しい人には react-hot-toast、かなりおすすめです!