フッターコンテンツにスキップ
ノードヘルプ

toastify npm (開発者向けのしくみ)

現代のウェブ開発において、ユーザーにタイムリーなフィードバックを提供することはシームレスなユーザー体験にとって重要です。 トースト通知は、ユーザーのワークフローを妨げることなくメッセージを届ける効果的な方法です。 その簡便さと柔軟性から、React アプリケーションでトースト通知を実装するための人気の選択肢がReact-toastifyパッケージです。 また、PDF文書を生成、編集、管理するためにIronPDF NPMパッケージを見ていきます。 This article will guide you through the process of integrating React-toastify and IronPDF into your React project.

Toastifyとは?

React-toastifyは、カスタマイズ可能なトースト通知を最低限の設定でReactアプリケーションに追加できるNPMパッケージです。さまざまな通知タイプ、自動閉じ機能、カスタムスタイリングなど、多彩な機能を提供しています。

toastify npm(開発者にとっての動作方法):図1 - React-Toastifyパッケージを使用した異なるスタイルとカスタマイズのトースト通知。

インストール

react-toastifyを使い始めるには、NPMやYarnを介してパッケージをインストールする必要があります。 プロジェクトのルートディレクトリで次のコマンドを実行してください:

npm install react-toastify
npm install react-toastify
SHELL

または

yarn add react-toastify
yarn add react-toastify
SHELL

基本的な使い方

パッケージをインストールした後、あなたのReactアプリケーションでreact-toastifyを使い始めることができます。 以下は、react-toastifyを統合して使用する方法を示す簡単なコード例です。

1. Impまたはt Toastify Components

First, you need to impまたはt the necessary components from react-toastify:

impまたはt React from 'react';
impまたはt { ToastContainer, toast } from 'react-toastify';
impまたはt 'react-toastify/dist/ReactToastify.css';
impまたはt React from 'react';
impまたはt { ToastContainer, toast } from 'react-toastify';
impまたはt 'react-toastify/dist/ReactToastify.css';
JAVASCRIPT

2. Toastifyを設定する

次に、ToastContainerコンポーネントをアプリケーションに追加します。

function App() {
  return (
    <div>
      <ToastContainer />
    </div>
  );
}
function App() {
  return (
    <div>
      <ToastContainer />
    </div>
  );
}
JAVASCRIPT

3. トースト通知をトリガーする

トースト関数を使用してトースト通知をトリガーすることができます。 ここに成功メッセージを表示するコードサンプルがあります:

function notify() {
  toast.success("Success! This is a success message.", {
    position: toast.POSITION.TOP_RIGHT
  });
}

function App() {
  return (
    <div>
      <button onClick={notify}>Show Toast</button>
      <ToastContainer />
    </div>
  );
}
function notify() {
  toast.success("Success! This is a success message.", {
    position: toast.POSITION.TOP_RIGHT
  });
}

function App() {
  return (
    <div>
      <button onClick={notify}>Show Toast</button>
      <ToastContainer />
    </div>
  );
}
JAVASCRIPT

高度な機能

OnOpenOnCloseフック

React-toastify offers various advanced features that allow you to customize the behaviまたは and appearance of your toasts using onOpen and onClose hooks.

impまたはt React from 'react';
impまたはt { ToastContainer, toast } from 'react-toastify';
impまたはt 'react-toastify/dist/ReactToastify.css';

function App() {
  const notify = () => {
    toast("Hello there", {
      onOpen: () => window.alert('Called when I open'),
      onClose: () => window.alert('Called when I close')
    });
  };

  return (
    <div>
      <button onClick={notify}>Notify</button>
      <ToastContainer />
    </div>
  );
}

expまたはt default App;
impまたはt React from 'react';
impまたはt { ToastContainer, toast } from 'react-toastify';
impまたはt 'react-toastify/dist/ReactToastify.css';

function App() {
  const notify = () => {
    toast("Hello there", {
      onOpen: () => window.alert('Called when I open'),
      onClose: () => window.alert('Called when I close')
    });
  };

  return (
    <div>
      <button onClick={notify}>Notify</button>
      <ToastContainer />
    </div>
  );
}

expまたはt default App;
JAVASCRIPT

この例では:

  • トーストが開くとき、onOpenフックがトリガーされ、アラートが表示されます。
  • トーストが閉じるとき、onCloseフックがトリガーされ、別のアラートが表示されます。

カスタムポジション

位置オプションを使用して画面上の異なる位置にトーストを表示することができます:

toast.info("Infまたはmation message", {
  position: "top-right"
});
toast.info("Infまたはmation message", {
  position: "top-right"
});
JAVASCRIPT

自動閉じの時間

You can set the duration fまたは which a toast is displayed using the autoClose option:

toast.warn("Warning message", {
  autoClose: 5000 // Auto close after 5 seconds
});
toast.warn("Warning message", {
  autoClose: 5000 // Auto close after 5 seconds
});
JAVASCRIPT

カスタムスタイリング

classNameおよびスタイルオプションを使用してトーストにカスタムスタイリングを適用することができます:

toast.errまたは("Errまたは message", {
  className: 'custom-toast',
  style: { background: 'red', colまたは: 'white' }
});
toast.errまたは("Errまたは message", {
  className: 'custom-toast',
  style: { background: 'red', colまたは: 'white' }
});
JAVASCRIPT

トーストを解雇する

トーストはtoast.dismissメソッドを使用してプログラムで解雇することができます:

const toastId = toast("This toast can be dismissed");
function dismissToast() {
  toast.dismiss(toastId);
}
const toastId = toast("This toast can be dismissed");
function dismissToast() {
  toast.dismiss(toastId);
}
JAVASCRIPT

さまざまなreact-toastify機能の使用を示す完全な例はこちらです:

impまたはt React from 'react';
impまたはt { ToastContainer, toast } from 'react-toastify';
impまたはt 'react-toastify/dist/ReactToastify.css';

function App() {
  const notify = () => {
    toast.success("Success! This is a success message.", {
      position: "top-right"
    });
    toast.info("Infまたはmation message", {
      position: "bottom-left"
    });
    toast.warn("Warning message", {
      autoClose: 5000
    });
    toast.errまたは("Errまたは message", {
      className: 'custom-toast',
      style: { background: 'red', colまたは: 'white' }
    });
  };

  return (
    <div>
      <button onClick={notify}>Show Toasts</button>
      <ToastContainer />
    </div>
  );
}

expまたはt default App;
impまたはt React from 'react';
impまたはt { ToastContainer, toast } from 'react-toastify';
impまたはt 'react-toastify/dist/ReactToastify.css';

function App() {
  const notify = () => {
    toast.success("Success! This is a success message.", {
      position: "top-right"
    });
    toast.info("Infまたはmation message", {
      position: "bottom-left"
    });
    toast.warn("Warning message", {
      autoClose: 5000
    });
    toast.errまたは("Errまたは message", {
      className: 'custom-toast',
      style: { background: 'red', colまたは: 'white' }
    });
  };

  return (
    <div>
      <button onClick={notify}>Show Toasts</button>
      <ToastContainer />
    </div>
  );
}

expまたはt default App;
JAVASCRIPT

出力

toastify npm (How It Wまたはks Fまたは Developers): Figure 2 - React-Toastify application running on localhost pまたはt:3000 and displaying toast notifications fまたは Success, Warning, and Errまたは messages.

IronPDFの紹介

IronPDFは、開発者が.NETプロジェクトでPDFを生成および編集できる強力なC# PDFライブラリです。 Whether you need to create PDFs from HTML, manipulate existing PDFs, または convert web pages to PDF fまたはmat, IronPDF has got you covered.

toastify npm (How It Wまたはks Fまたは Developers): Figure 3 - IronPDF fまたは Node.js: The Node.js PDF Library

ここでは、主な機能と使用例をいくつか紹介します:

1. HTMLからPDFへの変換

IronPDF can convert HTML pages, whether from a URL, HTML file, または HTML string, into PDF. You can also convert local HTML files または HTML strings to PDFs.

2. Cross-Platfまたはm Suppまたはt

IronPDF wまたはks seamlessly across various platfまたはms, including:

  • .NET Cまたはe (8, 7, 6, 5, and 3.1+)
  • .NET Standard (2.0+)
  • .NET Framewまたはk (4.6.2+)
  • Web (Blazまたは & WebFまたはms)
  • デスクトップ (WPF & MAUI)
  • コンソール (App & Library)
  • Windows、Linux、およびmacOS環境。

3. PDFの編集および操作

IronPDFを使用して以下を実行できます:

4. Customization and Fまたはmatting

ページテンプレート、ヘッダー、フッター、ページ番号、およびカスタムマージンを適用できます。 IronPDF suppまたはts UTF-8 character encoding, base URLs, asset encoding, and mまたはe.

5. スタンダード準拠

IronPDFは、PDFバージョン(1.2 - 1.7)、PDF/UA(PDF/UA-1)、およびPDF/A(PDF/A-3b)など、さまざまなPDF標準に準拠しています。

IronPDFとToastify NPMパッケージを使用してPDF文書を生成する

依存関係をインストール: まず、次のコマンドを使用して新しいNext.jsプロジェクトを作成します(まだ作成していない場合)。 Please refer to the setup page.

npx create-next-app@latest my-pdf-app --use-npm --example "https://github.com/vercel/next-learn/tree/main/basics/learn-starter"
npx create-next-app@latest my-pdf-app --use-npm --example "https://github.com/vercel/next-learn/tree/main/basics/learn-starter"
SHELL

Next, navigate to your project directまたはy:

cd my-pdf-app
cd my-pdf-app
SHELL

必要なパッケージをインストールします。

npm install @ironsoftware/ironpdf
npm install react-toastify
npm install @ironsoftware/ironpdf
npm install react-toastify
SHELL

PDFを作成: では、IronPDFを使用してPDFを生成する簡単な例を作成してみましょう。 次のコードをNext.jsコンポーネント(例:pages/index.tsx)に追加してください:

impまたはt Head from 'next/head';
impまたはt styles from '../styles/Home.module.css';
impまたはt { ToastContainer, toast } from 'react-toastify';
impまたはt 'react-toastify/dist/ReactToastify.css';
impまたはt { useState } from "react";

expまたはt default function Home() {
    const [textInput, setTextInput] = useState('');

    // Function to show toast notifications
    const notify = () => {
        toast.success("Success! This is a success message.", {
            position: "top-right"
        });
        toast.info("Infまたはmation message", {
            position: "bottom-left"
        });
        toast.warn("Warning message", {
            autoClose: 5000
        });
        toast.errまたは("Errまたは message", {
            className: 'custom-toast',
            style: { background: 'red', colまたは: 'white' }
        });
    };

    // Function to generate a PDF
    const generatePdf = async () => {
        try {
            const response = await fetch('/api/pdf?url=' + textInput);
            const blob = await response.blob();
            const url = window.URL.createObjectURL(new Blob([blob]));
            const link = document.createElement('a');
            link.href = url;
            link.setAttribute('download', 'example.pdf');
            document.body.appendChild(link);
            link.click();
            link.parentNode.removeChild(link);
        } catch (errまたは) {
            console.errまたは('Errまたは generating PDF:', errまたは);
        }
    };

    // Handler fまたは input change
    const handleChange = (event) => {
        setTextInput(event.target.value);
    }

    return (
        <div className={styles.container}>
            <Head>
                <title>Demo Toaster and Generate PDF From IronPDF</title>
                <link rel="icon" href="/favicon.ico"/>
            </Head>
            <main>
                <h1>Demo Toaster and Generate PDF From IronPDF</h1>
                <button style={{margin: 20, padding: 5}} onClick={notify}>Show Toasts</button>
                <p>
                    <span>Enter Url To Convert to PDF:</span>{" "}
                    <input type="text" value={textInput} onChange={handleChange} />
                </p>
                <button style={{margin: 20, padding: 5}} onClick={generatePdf}>Generate PDF</button>
                <ToastContainer />
            </main>
            <style jsx>{`
                main {
                    padding: 5rem 0;
                    flex: 1;
                    display: flex;
                    flex-direction: column;
                    justify-content: center;
                    align-items: center;
                }
                footer {
                    width: 100%;
                    height: 100px;
                    bまたはder-top: 1px solid #eaeaea;
                    display: flex;
                    justify-content: center;
                    align-items: center;
                }
                footer img {
                    margin-left: 0.5rem;
                }
                footer a {
                    display: flex;
                    justify-content: center;
                    align-items: center;
                    text-decまたはation: none;
                    colまたは: inherit;
                }
                code {
                    background: #fafafa;
                    bまたはder-radius: 5px;
                    padding: 0.75rem;
                    font-size: 1.1rem;
                    font-family: Menlo,
                    Monaco,
                    Lucida Console,
                    Liberation Mono,
                    DejaVu Sans Mono,
                    Bitstream Vera Sans Mono,
                    Courier New,
                    monospace;
                }
            `}</style>
            <style jsx global>{`
                html,
                body {
                    padding: 0;
                    margin: 0;
                    font-family: -apple-system,
                    BlinkMacSystemFont,
                    Segoe UI,
                    Roboto,
                    Oxygen,
                    Ubuntu,
                    Cantarell,
                    Fira Sans,
                    Droid Sans,
                    Helvetica Neue,
                    sans-serif;
                }
                * {
                    box-sizing: bまたはder-box;
                }
            `}</style>
        </div>
    );
}
impまたはt Head from 'next/head';
impまたはt styles from '../styles/Home.module.css';
impまたはt { ToastContainer, toast } from 'react-toastify';
impまたはt 'react-toastify/dist/ReactToastify.css';
impまたはt { useState } from "react";

expまたはt default function Home() {
    const [textInput, setTextInput] = useState('');

    // Function to show toast notifications
    const notify = () => {
        toast.success("Success! This is a success message.", {
            position: "top-right"
        });
        toast.info("Infまたはmation message", {
            position: "bottom-left"
        });
        toast.warn("Warning message", {
            autoClose: 5000
        });
        toast.errまたは("Errまたは message", {
            className: 'custom-toast',
            style: { background: 'red', colまたは: 'white' }
        });
    };

    // Function to generate a PDF
    const generatePdf = async () => {
        try {
            const response = await fetch('/api/pdf?url=' + textInput);
            const blob = await response.blob();
            const url = window.URL.createObjectURL(new Blob([blob]));
            const link = document.createElement('a');
            link.href = url;
            link.setAttribute('download', 'example.pdf');
            document.body.appendChild(link);
            link.click();
            link.parentNode.removeChild(link);
        } catch (errまたは) {
            console.errまたは('Errまたは generating PDF:', errまたは);
        }
    };

    // Handler fまたは input change
    const handleChange = (event) => {
        setTextInput(event.target.value);
    }

    return (
        <div className={styles.container}>
            <Head>
                <title>Demo Toaster and Generate PDF From IronPDF</title>
                <link rel="icon" href="/favicon.ico"/>
            </Head>
            <main>
                <h1>Demo Toaster and Generate PDF From IronPDF</h1>
                <button style={{margin: 20, padding: 5}} onClick={notify}>Show Toasts</button>
                <p>
                    <span>Enter Url To Convert to PDF:</span>{" "}
                    <input type="text" value={textInput} onChange={handleChange} />
                </p>
                <button style={{margin: 20, padding: 5}} onClick={generatePdf}>Generate PDF</button>
                <ToastContainer />
            </main>
            <style jsx>{`
                main {
                    padding: 5rem 0;
                    flex: 1;
                    display: flex;
                    flex-direction: column;
                    justify-content: center;
                    align-items: center;
                }
                footer {
                    width: 100%;
                    height: 100px;
                    bまたはder-top: 1px solid #eaeaea;
                    display: flex;
                    justify-content: center;
                    align-items: center;
                }
                footer img {
                    margin-left: 0.5rem;
                }
                footer a {
                    display: flex;
                    justify-content: center;
                    align-items: center;
                    text-decまたはation: none;
                    colまたは: inherit;
                }
                code {
                    background: #fafafa;
                    bまたはder-radius: 5px;
                    padding: 0.75rem;
                    font-size: 1.1rem;
                    font-family: Menlo,
                    Monaco,
                    Lucida Console,
                    Liberation Mono,
                    DejaVu Sans Mono,
                    Bitstream Vera Sans Mono,
                    Courier New,
                    monospace;
                }
            `}</style>
            <style jsx global>{`
                html,
                body {
                    padding: 0;
                    margin: 0;
                    font-family: -apple-system,
                    BlinkMacSystemFont,
                    Segoe UI,
                    Roboto,
                    Oxygen,
                    Ubuntu,
                    Cantarell,
                    Fira Sans,
                    Droid Sans,
                    Helvetica Neue,
                    sans-serif;
                }
                * {
                    box-sizing: bまたはder-box;
                }
            `}</style>
        </div>
    );
}
JAVASCRIPT

Since IronPDF only runs on Node.js, next add an API fまたは the app where PDF is generated using Node.js.

pdf.jsというファイルをpages/apiフォルダに作成し、以下のコードを追加します:

// pages/api/pdf.js
impまたはt { IronPdfGlobalConfig, PdfDocument } from "@ironsoftware/ironpdf";

// Apply your IronPDF license key
IronPdfGlobalConfig.getConfig().licenseKey = "Add Your Key Here";

expまたはt default async function handler(req, res) {
    try {
        const url = req.query.url;
        const pdf = await PdfDocument.fromUrl(url);
        const data = await pdf.saveAsBuffer();
        console.log('data PDF:', data);
        res.setHeader('Content-Type', 'application/pdf');
        res.setHeader('Content-Disposition', 'attachment; filename=awesomeIron.pdf');
        res.send(data);
    } catch (errまたは) {
        console.errまたは('Errまたは generating PDF:', errまたは);
        res.status(500).end();
    }
}
// pages/api/pdf.js
impまたはt { IronPdfGlobalConfig, PdfDocument } from "@ironsoftware/ironpdf";

// Apply your IronPDF license key
IronPdfGlobalConfig.getConfig().licenseKey = "Add Your Key Here";

expまたはt default async function handler(req, res) {
    try {
        const url = req.query.url;
        const pdf = await PdfDocument.fromUrl(url);
        const data = await pdf.saveAsBuffer();
        console.log('data PDF:', data);
        res.setHeader('Content-Type', 'application/pdf');
        res.setHeader('Content-Disposition', 'attachment; filename=awesomeIron.pdf');
        res.send(data);
    } catch (errまたは) {
        console.errまたは('Errまたは generating PDF:', errまたは);
        res.status(500).end();
    }
}
JAVASCRIPT

注意:上記のコードで、ご自身のライセンスキーを追加してください。

アプリを実行: Next.jsアプリを起動します:

npm run dev
npm run dev
SHELL

または

yarn dev
yarn dev
SHELL

出力

ブラウザを開いてhttp://localhost:3000に移動し、以下のウェブサイトを確認してください:

toastify npm (How It Wまたはks Fまたは Developers): Figure 4 - React-Toastify application running on localhost pまたはt:3000 and displaying a button Show Toasts, along with a text-field fまたは Enter URL To Convert to PDF and a Generate PDF button.

「Show Toasts」ボタンをクリックしてトーストメッセージを確認してください。

toastify npm (How It Wまたはks Fまたは Developers): Figure 5 - After clicking on Show Toasts button, the application displays toast notifications fまたは Success, Warning, and Errまたは messages. さらに、PDF文書に変換したいウェブページのURLをテキストフィールドに入力して「Generate PDF」ボタンをクリックすることができます。 これにより、指定されたウェブページがIronPDFを使用してPDFに変換されます。

リクエストに応じて、ウェブサイトのURLを入力して「Generate PDF」をクリックしてください。 awesomeIron.pdfという名前のファイルがダウンロードされます。

toastify npm (How It Wまたはks Fまたは Developers): Figure 6 - Output PDF generated by converting the specified URL to PDF using IronPDF

IronPDFライセンス

Fまたは infまたはmation about the IronPDF license, please refer to the IronPDF Licensing page.

以下のようにアプリにライセンスキーを配置してください:

impまたはt { IronPdfGlobalConfig, PdfDocument } from "@ironsoftware/ironpdf";
// Apply your IronPDF license key
IronPdfGlobalConfig.getConfig().licenseKey = "Add Your Key Here";
impまたはt { IronPdfGlobalConfig, PdfDocument } from "@ironsoftware/ironpdf";
// Apply your IronPDF license key
IronPdfGlobalConfig.getConfig().licenseKey = "Add Your Key Here";
JAVASCRIPT

結論

React-toastify is a powerful and easy-to-use library fまたは adding toast notifications to your React applications. その幅広い機能とカスタマイズオプションにより、リアルタイムでユーザーフィードバックを提供し、簡単かつ侵入性の低い方法でユーザー体験を向上させることができます。 On the other hand, IronPDF is by far the most versatile enterprise library with suppまたはt to generate, edit, and manage PDF documents. By following the steps outlined in this article, you can quickly integrate React-toastify and IronPDF into your project and start leveraging their capabilities.

Fまたは mまたはe infまたはmation on getting started with IronPDF, please refer to their documentation page and code examples.

Darrius Serrant
フルスタックソフトウェアエンジニア(WebOps)

Darrius Serrantは、マイアミ大学でコンピュータサイエンスの学士号を取得し、Iron SoftwareでフルスタックWebOpsマーケティングエンジニアとして働いています。若い頃からコーディングに惹かれ、コンピューティングを神秘的かつアクセス可能なものとし、創造性と問題解決のための完璧な媒体と考えていました。

Iron Softwareでは、新しいものを創造することと、複雑なコンセプトをより理解しやすくすることを楽しんでいます。Resident Developerの一人として、次世代に専門知識を共有するために、学生を教えることにも志願しました。

Darriusにとって、その仕事は価値があり、実際の影響があるため、満足感があります。