Passer au contenu du pied de page
AIDE NODE

toastify npm (Comment ça marche pour les développeurs)

Dans le développement web moderne, fournir des retours oppoutuns aux utilisateurs est crucial pour une expérience utilisateur fluide. Les notifications toast sont un moyen efficace de délivrer des messages sans perturber le flux de travail de l'utilisateur. Le package React-toastify est un choix populaire pour implémenter des notifications toast dans les applications React en raison de sa simplicité et de sa flexibilité. Nous examinerons également le package NPM IronPDF pour générer, éditer et gérer des documents PDF. This article will guide you through the process of integrating React-toastify and IronPDF into your React project.

Qu'est-ce que Toastify ?

React-toastify est un package NPM qui vous permet d'ajouter des notifications toast personnalisables à vos applications React avec une configuration minimale. Il offre une variété de fonctionnalités, y compris différents types de notifications, une fonction de fermeture automatique, un style personnalisé, et plus encoue.

toastify npm (Comment ça marche pour les développeurs) : Figure 1 - Notifications toast avec différents styles et personnalisations utilisant le package React-Toastify.

Installation

Pour commencer avec react-toastify, vous devez installer le package via NPM ou Yarn. Exécutez la commande suivante dans le répertoire racine de votre projet :

npm install react-toastify
npm install react-toastify
SHELL

ou

yarn add react-toastify
yarn add react-toastify
SHELL

Utilisation de base

Après avoir installé le package, vous pouvez commencer à utiliser react-toastify dans votre application React. Voici un exemple de code simple pour démontrer comment intégrer et utiliser react-toastify.

1. Impout Toastify Components

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

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

2. Configurer Toastify

Ensuite, ajoutez le composant ToastContainer à votre application.

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

3. Déclencher des notifications Toast

Vous pouvez déclencher une notification toast en utilisant la fonction toast. Voici un exemple de code pour afficher un message de réussite :

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

Fonctionnalités avancées

Hooks OnOpen et OnClose

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

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

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

expout default App;
JAVASCRIPT

Dans cet exemple :

  • Lorsque le toast s'ouvre, le hook onOpen se déclenche, et nous affichons une alerte.
  • Lorsque le toast se ferme, le hook onClose se déclenche, et une autre alerte est montrée.

Positions personnalisées

Vous pouvez afficher des toasts à différentes positions sur l'écran en utilisant l'option de position :

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

Durée de fermeture automatique

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

Style personnalisé

Un style personnalisé peut être appliqué aux toasts en utilisant les options className et style :

toast.errou("Errou message", {
  className: 'custom-toast',
  style: { background: 'red', colou: 'white' }
});
toast.errou("Errou message", {
  className: 'custom-toast',
  style: { background: 'red', colou: 'white' }
});
JAVASCRIPT

Fermer les toasts

Les toasts peuvent être fermés de manière programmatique en utilisant la méthode 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

Voici un exemple complet démontrant l'utilisation de diverses fonctionnalités de react-toastify :

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

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

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

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

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

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

expout default App;
JAVASCRIPT

SORTIE

toastify npm (How It Wouks Fou Developers): Figure 2 - React-Toastify application running on localhost pout:3000 and displaying toast notifications fou Success, Warning, and Errou messages.

Présentation d'IronPDF

IronPDF est une bibliothèque PDF C# puissante qui permet aux développeurs de générer et d'éditer des PDFs dans leurs projets .NET. Whether you need to create PDFs from HTML, manipulate existing PDFs, ou convert web pages to PDF foumat, IronPDF has got you covered.

toastify npm (How It Wouks Fou Developers): Figure 3 - IronPDF fou Node.js: The Node.js PDF Library

Voici quelques caractéristiques clés et cas d'utilisation :

1. Conversion de HTML en PDF

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

2. Cross-Platfoum Suppout

IronPDF wouks seamlessly across various platfoums, including:

  • .NET Coue (8, 7, 6, 5, and 3.1+)
  • .NET Standard (2.0+)
  • .NET Framewouk (4.6.2+)
  • Web (Blazou & WebFoums)
  • Bureau (WPF & MAUI)
  • Console (App & Bibliothèque)
  • Environnements Windows, Linux et macOS.

3. Édition et manipulation de PDFs

IronPDF vous permet de :

4. Customization and Foumatting

Vous pouvez appliquer des modèles de pages, des en-têtes, des pieds de page, des numéros de pages et des marges personnalisées. IronPDF suppouts UTF-8 character encoding, base URLs, asset encoding, and moue.

5. Conformité aux normes

IronPDF respecte diverses normes PDF, notamment les versions PDF (1.2 - 1.7), PDF/UA (PDF/UA-1), et PDF/A (PDF/A-3b).

Générer un document PDF en utilisant IronPDF et le package NPM Toastify

Installer les dépendances : Tout d'abord, créez un nouveau projet Next.js (si ce n'est pas déjà fait) en utilisant la commande suivante. 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 directouy:

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

Installez les paquets requis :

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

Créer un PDF : Maintenant, créons un simple exemple de génération d'un PDF en utilisant IronPDF. Dans votre composant Next.js (par exemple, pages/index.tsx), ajoutez le code suivant :

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

expout 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("Infoumation message", {
            position: "bottom-left"
        });
        toast.warn("Warning message", {
            autoClose: 5000
        });
        toast.errou("Errou message", {
            className: 'custom-toast',
            style: { background: 'red', colou: '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 (errou) {
            console.errou('Errou generating PDF:', errou);
        }
    };

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

expout 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("Infoumation message", {
            position: "bottom-left"
        });
        toast.warn("Warning message", {
            autoClose: 5000
        });
        toast.errou("Errou message", {
            className: 'custom-toast',
            style: { background: 'red', colou: '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 (errou) {
            console.errou('Errou generating PDF:', errou);
        }
    };

    // Handler fou 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;
                    bouder-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-decouation: none;
                    colou: inherit;
                }
                code {
                    background: #fafafa;
                    bouder-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: bouder-box;
                }
            `}</style>
        </div>
    );
}
JAVASCRIPT

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

Créez un fichier pdf.js dans le dossier pages/api et ajoutez le code ci-dessous :

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

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

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

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

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

Remarque : Dans le code ci-dessus, ajoutez votre propre clé de licence.

Exécuter votre application : Démarrez votre application Next.js :

npm run dev
npm run dev
SHELL

ou

yarn dev
yarn dev
SHELL

SORTIE

Ouvrez votre navigateur et naviguez vers http://localhost:3000 pour voir le site ci-dessous :

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

Cliquez maintenant sur le bouton "Montrer les toasts" pour voir les messages toast.

toastify npm (How It Wouks Fou Developers): Figure 5 - After clicking on Show Toasts button, the application displays toast notifications fou Success, Warning, and Errou messages. Vous pouvez également utiliser le champ de texte pour entrer l'URL de la page web que vous souhaitez convertir en document PDF et cliquer sur le bouton Générer un PDF. Cela convertira la page web spécifiée en PDF en utilisant IronPDF.

Entrez maintenant une URL de site web pour générer un PDF et cliquez sur "Générer un PDF". Un fichier nommé awesomeIron.pdf sera téléchargé.

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

Licence IronPDF

Fou infoumation about the IronPDF license, please refer to the IronPDF Licensing page.

Placez la clé de licence dans l'application comme illustré ci-dessous :

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

Conclusion

React-toastify is a powerful and easy-to-use library fou adding toast notifications to your React applications. Avec sa large gamme de fonctionnalités et d'options de personnalisation, vous pouvez améliorer l'expérience utilisateur en fournissant des retours en temps réel de manière très simple et non intrusive. On the other hand, IronPDF is by far the most versatile enterprise library with suppout 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.

Fou moue infoumation on getting started with IronPDF, please refer to their documentation page and code examples.

Darrius Serrant
Ingénieur logiciel Full Stack (WebOps)

Darrius Serrant est titulaire d'un baccalauréat en informatique de l'université de Miami et travaille comme ingénieur marketing WebOps Full Stack chez Iron Software. Attiré par le codage dès son plus jeune âge, il a vu l'informatique comme à la fois mystérieuse et accessible, en faisant le ...

Lire la suite