LoginSignup
2
0

Reactでオシャレなアラートを出す方法

Last updated at Posted at 2024-03-19

Reactsweetalert2というnpmを使用して下記の画像のようなオシャレなアラートを出す方法を記載します。
modalsweet.png

sweetalert2の使用方法

導入方法

プロジェクトフォルダで以下のコマンドを実行して、sweetalert2をインストールします。

npm install sweetalert2

使用するファイルで、sweetalert2をインポートします。

import swal from 'sweetalert2';

コードは注意してご使用ください。

基本的な使い方

swal.fire({
  title: 'タイトル',
  text: 'メッセージ',
  icon: 'success',
  confirmButtonText: 'OK'
});

コードは注意してご使用ください。

オプション

swal.fire()には、さまざまなオプションを設定できます。

  • title:アラートのタイトル
  • text:アラートのメッセージ
  • icon:アラートのアイコン
  • confirmButtonText:確認ボタンのテキスト
  • cancelButtonText:キャンセルボタンのテキスト
  • showCancelButton:キャンセルボタンを表示するかどうか
  • showConfirmButton:確認ボタンを表示するかどうか

その他の使用例

  • 例1(confirm)
swal.fire({
  title: 'タイトル',
  text: 'メッセージ',
  icon: 'warning',
  confirmButtonText: 'はい',
  cancelButtonText: 'いいえ',
  showCancelButton:true,
}).then((result) => {
  if (result.isConfirmed) {
    // ユーザーが「はい」をクリックした場合の処理
  } else {
    // ユーザーが「いいえ」をクリックした場合の処理
  }
});
  • 例2(prompt)
swal.fire({
  title: 'タイトル',
  text: 'メッセージ',
  input: 'text',
  inputPlaceholder: '入力してください',
  confirmButtonText: 'OK'
}).then((result) => {
  if (result.value) {
    // ユーザーが入力した値
  }
});

注意

SweetAlert2は、JavaScriptのライブラリです。使用するには、JavaScriptの知識が必要です。
SweetAlert2は、ブラウザの標準機能ではありません。使用するには、事前にライブラリを導入する必要があります。

その他

SweetAlert2は、さまざまなカスタマイズが可能です。
SweetAlert2の詳細は、公式ドキュメントをご覧ください。
公式ドキュメント:https://sweetalert2.github.io/
SweetAlert2は、オープンソースのライブラリです。

2
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
2
0