0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【React】shadcn/ui の toast を使ってみる

Posted at

はじめに

こんにちは。アメリカ在住で独学エンジニアを目指している Taira です。

Rails 開発を経験した後、SPA 開発をしていると、Rails の flash のような通知機能ほしいなと思うことはありませんか?

調べていくと、Web アプリケーションでは「操作が成功したのか」「エラーが発生したのか」をユーザーに伝えるために トースト通知(toast notification) が使われることを知りました

shadcn/ui では、sooner をベースとした Toaster コンポーネントを利用できます。
この記事では、その導入方法と基本的な使い方を紹介します。


セットアップ

まずは sonner を追加します。

npx shadcn-ui@latest add sonner

すると、<Toaster /> コンポーネントと toast 関数が使えるようになります。

次に、アプリのルート(例: App.tsx)に Toaster を配置します。

import { Toaster } from '@/components/ui/sonner';

function App() {
  return (
    <>
      <Routes />
      <Toaster richColors position="top-right" />
    </>
  );
}

ここで richColors を指定すると、成功・失敗・警告などに応じて色が自動で適用されます。


基本的な使い方

通知は toast 関数を呼び出すだけです。

import { toast } from 'sonner';

// 成功
toast.success('講師を削除しました。');

// 失敗
toast.error('講師の削除に失敗しました。');

// 情報
toast.info('読み込み中です...');

// 警告
toast.warning('確認が必要です。');

<Toaster richColors /> を指定していると、

  • success → 緑
  • error → 赤
  • info → 青
  • warning → 黄

といった色が自動で反映されます。


まとめ

  • shadcn/ui で toast を使うには npx shadcn-ui@latest add sonner を実行する
  • <Toaster richColors /> をルートに配置すれば、成功/失敗/警告などに応じて色が自動で付く
  • toast.success / toast.error / toast.info / toast.warning を呼ぶだけで簡単に通知を出せる
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?