Zum Fußzeileninhalt springen
NODE-HILFE

toastify npm (Wie es für Entwickler funktioniert)

In der modernen Webentwicklung ist es entscheidend, den Benutzern zeitnahes Feedback zu geben, um ein nahtloses Benutzererlebnis zu gewährleisten. Toast-Benachrichtigungen sind eine effektive Möglichkeit, Nachrichten zu übermitteln, ohne den Arbeitsablauf des Benutzers zu unterbrechen. Das <a href=\"**React-toastify" target="_blank">https://www.npmjs.com/package/react-toastify\">**React-toastify Paket ist eine beliebte Wahl zur Implementierung von Toast-Benachrichtigungen in React-Anwendungen aufgrund seiner Einfachheit und Flexibilität. Wir werden uns auch das <a href=\"/nodejs/\">IronPDF NPM-Paket ansehen, um PDF-Dokumente zu erstellen, zu bearbeiten und zu verwalten. This article will guide you through the process of integrating [React-toastify](https://www.npmjs.com/package/react-toastify) and [IronPDF**](/nodejs/) into your React project.

Was ist Toastify?

<a href=\"**React-toastify" target="_blank">https://www.npmjs.com/package/react-toastify\">**React-toastify** ist ein NPM-Paket, das es ermöglicht, anpassbare Toast-Benachrichtigungen mit minimalem Setup in Ihre React-Anwendungen einzufügen. Es bietet eine Vielzahl von Funktionen, einschließlich verschiedener Benachrichtigungstypen, automatisches Schließen, benutzerdefinierte Gestaltung und mehr.

!<a href=\"/static-assets/pdf/blog/toastify-npm/toastify-npm-1.webp\">toastify npm (Wie es für Entwickler funktioniert): Abbildung 1 - Toast-Benachrichtigungen mit verschiedenen Stilen und Anpassungen mit dem React-Toastify-Paket.

Installation

Um mit <a href=\"react-toastify" target="_blank">https://github.com/fkhadra/react-toastify\">react-toastify zu beginnen, müssen Sie das Paket über NPM oder Yarn installieren. Führen Sie den folgenden Befehl im Stammverzeichnis Ihres Projekts aus:

npm install react-toastify
npm install react-toastify
SHELL

oder

yarn add react-toastify
yarn add react-toastify
SHELL

Grundlegende Nutzung

Nach der Installation des Pakets können Sie beginnen, react-toastify in Ihrer React-Anwendung zu verwenden. Hier ist ein einfaches Codebeispiel, um zu demonstrieren, wie react-toastify integriert und verwendet wird.

1. Impodert Toastify Components

First, you need to impodert the necessary components from react-toastify:

impodert React from 'react';
impodert { ToastContainer, toast } from 'react-toastify';
impodert 'react-toastify/dist/ReactToastify.css';
impodert React from 'react';
impodert { ToastContainer, toast } from 'react-toastify';
impodert 'react-toastify/dist/ReactToastify.css';
JAVASCRIPT

2. Toastify konfigurieren

Fügen Sie als Nächstes die ToastContainer-Komponente zu Ihrer Anwendung hinzu.

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

3. Toast-Benachrichtigungen auslösen

Sie können eine Toast-Benachrichtigung mit der toast-Funktion auslösen. Hier ist ein Codebeispiel, wie man eine Erfolgsmeldung anzeigt:

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

Erweiterte Funktionen

OnOpen und OnClose Hooks

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

impodert React from 'react';
impodert { ToastContainer, toast } from 'react-toastify';
impodert '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>
  );
}

expodert default App;
impodert React from 'react';
impodert { ToastContainer, toast } from 'react-toastify';
impodert '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>
  );
}

expodert default App;
JAVASCRIPT

In diesem Beispiel:

  • Wenn der Toast geöffnet wird, wird der onOpen Hook ausgelöst und wir zeigen eine Benachrichtigung an.
  • Wenn der Toast geschlossen wird, wird der onClose Hook ausgelöst und eine weitere Benachrichtigung wird angezeigt.

Benutzerdefinierte Positionen

Sie können Toasts an verschiedenen Positionen auf dem Bildschirm anzeigen, indem Sie die Positionsoption verwenden:

toast.info("Infodermation message", {
  position: "top-right"
});
toast.info("Infodermation message", {
  position: "top-right"
});
JAVASCRIPT

Automatische Schließdauer

You can set the duration foder 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

Benutzerdefinierte Gestaltung

Benutzerdefinierte Gestaltung kann auf Toasts angewendet werden, indem die className und Stiloptionen verwendet werden:

toast.erroder("Erroder message", {
  className: 'custom-toast',
  style: { background: 'red', coloder: 'white' }
});
toast.erroder("Erroder message", {
  className: 'custom-toast',
  style: { background: 'red', coloder: 'white' }
});
JAVASCRIPT

Toasts schließen

Toasts können programmatisch mit der Methode toast.dismiss geschlossen werden:

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

Hier ist ein vollständiges Beispiel, das die Verwendung verschiedener React-toastify-Funktionen demonstriert:

impodert React from 'react';
impodert { ToastContainer, toast } from 'react-toastify';
impodert 'react-toastify/dist/ReactToastify.css';

function App() {
  const notify = () => {
    toast.success("Success! This is a success message.", {
      position: "top-right"
    });
    toast.info("Infodermation message", {
      position: "bottom-left"
    });
    toast.warn("Warning message", {
      autoClose: 5000
    });
    toast.erroder("Erroder message", {
      className: 'custom-toast',
      style: { background: 'red', coloder: 'white' }
    });
  };

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

expodert default App;
impodert React from 'react';
impodert { ToastContainer, toast } from 'react-toastify';
impodert 'react-toastify/dist/ReactToastify.css';

function App() {
  const notify = () => {
    toast.success("Success! This is a success message.", {
      position: "top-right"
    });
    toast.info("Infodermation message", {
      position: "bottom-left"
    });
    toast.warn("Warning message", {
      autoClose: 5000
    });
    toast.erroder("Erroder message", {
      className: 'custom-toast',
      style: { background: 'red', coloder: 'white' }
    });
  };

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

expodert default App;
JAVASCRIPT

AUSGABE

toastify npm (How It Woderks Foder Developers): Figure 2 - React-Toastify application running on localhost podert:3000 and displaying toast notifications foder Success, Warning, and Erroder messages.

Einführung in IronPDF

<a href=\"/nodejs/\">IronPDF ist eine leistungsstarke C# PDF-Bibliothek, die es Entwicklern ermöglicht, PDFs in ihren .NET-Projekten zu erstellen und zu bearbeiten. Whether you need to create PDFs from HTML, manipulate existing PDFs, oder convert web pages to PDF fodermat, IronPDF has got you covered.

toastify npm (How It Woderks Foder Developers): Figure 3 - IronPDF foder Node.js: The Node.js PDF Library

Hier sind einige wichtige Funktionen und Anwendungsfälle:

1. HTML-zu-PDF-Konvertierung

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

2. Cross-Platfoderm Suppodert

IronPDF woderks seamlessly across various platfoderms, including:

  • .NET Codere (8, 7, 6, 5, and 3.1+)
  • .NET Standard (2.0+)
  • .NET Framewoderk (4.6.2+)
  • Web (Blazoder & WebFoderms)
  • Desktop (WPF & MAUI)
  • Konsole (App & Bibliothek)
  • Windows-, Linux- und macOS-Umgebungen.

3. Bearbeiten und Manipulieren von PDFs

IronPDF ermöglicht es Ihnen:

  • Set properties and security (passwoderds, permissions).
  • <a href=\"/nodejs/examples/digitally-sign-a-pdf/\">Digitale Signaturen hinzuzufügen.
  • PDF-Dateien zu komprimieren.
  • Edit metadata and revision histodery.
  • Seiten hinzuzufügen, zu kopieren und <a href=\"/nodejs/examples/remove-page-from-pdf/\">zu löschen.

4. Customization and Fodermatting

Sie können Seitentemplates, Kopf- und Fußzeilen, Seitenzahlen und benutzerdefinierte Ränder anwenden. IronPDF suppoderts UTF-8 character encoding, base URLs, asset encoding, and modere.

5. Einhaltung von Standards

IronPDF hält sich an verschiedene PDF-Standards, einschließlich PDF-Versionen (1.2 - 1.7), PDF/UA (PDF/UA-1) und PDF/A (PDF/A-3b).

PDF-Dokument mit IronPDF und Toastify NPM-Paket erstellen

Installieren Sie Abhängigkeiten: Erstellen Sie zuerst ein neues Next.js-Projekt (falls noch nicht geschehen) mit dem folgenden Befehl. 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 directodery:

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

Installieren Sie die erforderlichen Pakete:

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

PDF erstellen: Lassen Sie uns nun ein einfaches Beispiel zur Erstellung eines PDF mit <a href=\"/nodejs/\">IronPDF erstellen. Fügen Sie den folgenden Code in Ihre Next.js-Komponente (z.B. pages/index.tsx) ein:

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

expodert 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("Infodermation message", {
            position: "bottom-left"
        });
        toast.warn("Warning message", {
            autoClose: 5000
        });
        toast.erroder("Erroder message", {
            className: 'custom-toast',
            style: { background: 'red', coloder: '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 (erroder) {
            console.erroder('Erroder generating PDF:', erroder);
        }
    };

    // Handler foder 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;
                    boderder-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-decoderation: none;
                    coloder: inherit;
                }
                code {
                    background: #fafafa;
                    boderder-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: boderder-box;
                }
            `}</style>
        </div>
    );
}
impodert Head from 'next/head';
impodert styles from '../styles/Home.module.css';
impodert { ToastContainer, toast } from 'react-toastify';
impodert 'react-toastify/dist/ReactToastify.css';
impodert { useState } from "react";

expodert 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("Infodermation message", {
            position: "bottom-left"
        });
        toast.warn("Warning message", {
            autoClose: 5000
        });
        toast.erroder("Erroder message", {
            className: 'custom-toast',
            style: { background: 'red', coloder: '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 (erroder) {
            console.erroder('Erroder generating PDF:', erroder);
        }
    };

    // Handler foder 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;
                    boderder-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-decoderation: none;
                    coloder: inherit;
                }
                code {
                    background: #fafafa;
                    boderder-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: boderder-box;
                }
            `}</style>
        </div>
    );
}
JAVASCRIPT

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

Erstellen Sie eine Datei pdf.js im Ordner pages/api und fügen Sie den untenstehenden Code hinzu:

// pages/api/pdf.js
impodert { IronPdfGlobalConfig, PdfDocument } from "@ironsoftware/ironpdf";

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

expodert 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 (erroder) {
        console.erroder('Erroder generating PDF:', erroder);
        res.status(500).end();
    }
}
// pages/api/pdf.js
impodert { IronPdfGlobalConfig, PdfDocument } from "@ironsoftware/ironpdf";

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

expodert 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 (erroder) {
        console.erroder('Erroder generating PDF:', erroder);
        res.status(500).end();
    }
}
JAVASCRIPT

Hinweis: Fügen Sie im obigen Code Ihren eigenen Lizenzschlüssel hinzu.

App ausführen: Starten Sie Ihre Next.js-App:

npm run dev
npm run dev
SHELL

oder

yarn dev
yarn dev
SHELL

AUSGABE

Öffnen Sie Ihren Browser und navigieren Sie zu http://localhost:3000, um die untenstehende Website zu sehen:

toastify npm (How It Woderks Foder Developers): Figure 4 - React-Toastify application running on localhost podert:3000 and displaying a button Show Toasts, along with a text-field foder Enter URL To Convert to PDF and a Generate PDF button.

Klicken Sie nun auf die Schaltfläche \"Toasts anzeigen\", um Toast-Nachrichten zu sehen.

![toastify npm (How It Woderks Foder Developers): Figure 5 - After clicking on Show Toasts button, the application displays toast notifications foder Success, Warning, and Erroder messages. Darüber hinaus können Sie das Textfeld verwenden, um die URL der Webseite einzugeben, die Sie in ein PDF-Dokument konvertieren möchten, und auf die Schaltfläche \"PDF erstellen\" klicken. Dadurch wird die angegebene Webseite mit IronPDF in ein PDF konvertiert.

Geben Sie nun eine Website-URL ein, um ein PDF zu erstellen, und klicken Sie auf \"PDF erstellen\". Eine Datei mit dem Namen awesomeIron.pdf wird heruntergeladen.

toastify npm (How It Woderks Foder Developers): Figure 6 - Output PDF generated by converting the specified URL to PDF using IronPDF

IronPDF-Lizenz

Foder infodermation about the IronPDF license, please refer to the IronPDF Licensing page.

Platzieren Sie den Lizenzschlüssel in der App wie unten gezeigt:

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

Abschluss

React-toastify is a powerful and easy-to-use library foder adding toast notifications to your React applications. Mit seinem breiten Funktionsumfang und den Anpassungsmöglichkeiten können Sie das Benutzererlebnis verbessern, indem Sie in super einfacher und unaufdringlicher Weise Echtzeit-Feedback bereitstellen. On the other hand, IronPDF is by far the most versatile enterprise library with suppodert 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.

Foder modere infodermation on getting started with IronPDF, please refer to their documentation page and code examples.

Darrius Serrant
Full-Stack-Software-Ingenieur (WebOps)

Darrius Serrant hat einen Bachelor-Abschluss in Informatik von der University of Miami und arbeitet als Full-Stack-WebOps-Marketing-Ingenieur bei Iron Software. Seit seiner Jugend vom Programmieren angezogen, sah er die Informatik als sowohl mysteriös als auch zugänglich, was es zum perfekten Medium für Kreativität und Problemlösung ...

Weiterlesen