NODE HELP

toastify npm (How It Works For Developers)

Published September 29, 2024
Share:

Introduction

In modern web development, providing timely feedback to users is crucial for a seamless user experience. Toast notifications are an effective way to deliver messages without disrupting the user's workflow. The React-toastify package is a popular choice for implementing toast notifications in React applications due to its simplicity and flexibility. We will also look into IronPDF NPM package to generate, edit and manage PDF documents. This article will guide you through the process of integrating React-toastify and IronPDF into your React project.

What is Toastify?

React-toastify is an NPM package that allows you to add customizable toast notifications to your React applications with minimal setup. It provides a variety of features, including different notification types, auto-close functionality, custom styling, remaining time possibility and more.

toastify npm (How It Works For Developers): Figure 1 - Toast notifications with different styles and customizations using React-Toastify package.

Installation

To get started with react-toastify, you need to install the package via NPM or Yarn. Run the following command in your project's root directory:

npm install react-toastify

or

yarn add react-toastify

Basic Usage

After installing the package, you can start using react-toastify in your React application. Below is a simple code example to demonstrate how to integrate and use react-toastify.

1. Import Toastify Components

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

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

2. Configure Toastify

Next, add the ToastContainer component to your application.

function App() {
  return (
    <div>  // react component rendered inside
      <ToastContainer />
    </div>
  );
}
JAVASCRIPT

3. Trigger Toast Notifications

You can trigger a toast notification using the toast function. Here’s a code sample of how to display a success message:

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 /> // react component inside
    </div>
  );
}
JAVASCRIPT

Advanced Features

OnOpen and OnClose hooks

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

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

In this example:

  • When the toast opens, the onOpen hook triggers, and we display an alert.
  • When the toast closes, the onClose hook triggers, and another alert is shown.

Custom Positions

You can display toasts in different positions on the screen using the position option:

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

Auto-Close Duration

You can set the duration for which a toast is displayed using the autoClose option:

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

Custom Styling

Custom styling can be applied to toasts using the className and style options:

toast.error("Error message", {
  className: 'custom-toast',
  style: { background: 'red', color: 'white' }
});
JAVASCRIPT

Dismissing Toasts

Toasts can be programmatically dismissed using the toast.dismiss method:

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

Here’s a complete example demonstrating the use of various react-toastify features:

import React from 'react';
import { ToastContainer, toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
function App() {
  const notify = () => {
    toast.success("Success! This is a success message.", {
      position:"top-right"  // success notification
    });
    toast.info("Information message", {
      position:"bottom-left"  // info will be displayed with progress bar
    });
    toast.warn("Warning message", {
      autoClose: 5000 // close or pause toast messages
    });
    toast.error("Error message", {
      className: 'custom-toast',
      style: { background: 'red', color: 'white' }
    });
  };
  return (
    <div>
      <button onClick={notify}>Show Toasts</button>
      <ToastContainer />
    </div>
  );
}
export default App;
JAVASCRIPT

OUTPUT

toastify npm (How It Works For Developers): Figure 2 - React-Toastify application running on localhost post:3000 and displaying toast notifications for Success, Warning ad Error messages.

Introducing IronPDF

IronPDF is a powerful C# PDF library that allows developers to generate and edit PDFs in their .NET projects. Whether you need to create PDFs from HTML, manipulate existing PDFs, or convert web pages to PDF format, IronPDF has got you covered.

toastify npm (How It Works For Developers): Figure 3 - IronPDF for Node.js: The Node.js PDF Library

Here are some key features and use cases:

1. HTML to PDF Conversion

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

2. Cross-Platform Support

IronPDF works seamlessly across various platforms, including:

  • .NET Core (8, 7, 6, 5, and 3.1+)
  • .NET Standard (2.0+)
  • .NET Framework (4.6.2+)
  • Web (Blazor & WebForms)
  • Desktop (WPF & MAUI)
  • Console (App & Library)
  • Windows, Linux, and macOS environments.

3. Editing and Manipulating PDFs

IronPDF allows you to:

4. Customization and Formatting

You can apply page templates, headers, footers, page numbers, and custom margins. IronPDF supports UTF-8 character encoding, base URLs, asset encoding, and more.

5. Standards Compliance

IronPDF adheres to various PDF standards, including PDF versions (1.2 - 1.7), PDF/UA (PDF/UA-1), and PDF/A (PDF/A-3b).

Generate PDF Document Using IronPDF and Toastify NPM package

Install Dependencies: First, create a new Next.js project (if you haven’t already) using the following command: 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"

Next, navigate to your project directory:

cd my-pdf-app

Install the required packages:

npm install @ironsoftware/ironpdf
npm install react-toastify

Create a PDF: Now, let’s create a simple example of generating a PDF using IronPDF. In your Next.js component (e.g., pages/index.tsx), add the following code:

import Head from 'next/head';
import styles from '../styles/Home.module.css';
import {ToastContainer, toast} from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import {useState} from "react";
export default function Home() {
    const [textInput, setTextInput] = useState('');
    const notify = () => {
        toast.success("Success! This is a success message.", {
            position: "top-right"
        });
        toast.info("Information message", {
            position: "bottom-left"
        });
        toast.warn("Warning message", {
            autoClose: 5000
        });
        toast.error("Error message", {
            className: 'custom-toast',
            style: {background: 'red', color: 'white'}
        });
    };
    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 (error) {
            console.error('Error generating PDF:', error);
        }
    };
    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>{" "}
                </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;
                    border-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-decoration: none;
                    color: inherit;
                }
                code {
                    background: #fafafa;
                    border-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: border-box;
                }
            `}</style>
        </div>
    );
}
JAVASCRIPT

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

Create a file pdf.js at pages/api folder and add below code

// pages/api/pdf.js
import {IronPdfGlobalConfig, PdfDocument} from "@ironsoftware/ironpdf";
// Apply your IronPDF license key
IronPdfGlobalConfig.getConfig().licenseKey = "Add Your key here";
export default async function handler(req, res) {
    try {
        const url = req.query.url
        const pdf = await PdfDocument.fromUrl(url);
        const data = await pdf.saveAsBuffer();
        console.error('data PDF:', data);
        res.setHeader('Content-Type', 'application/pdf');
        res.setHeader('Content-Disposition', 'attachment; filename=awesomeIron.pdf');
        res.send(data);
    } catch (error) {
        console.error('Error generating PDF:', error);
        res.status(500).end();
    }
}
JAVASCRIPT

Note: In the above code add your own license key

Run Your App: Start your Next.js app:

npm run dev
or
yarn dev

OUTPUT

Open your browser and navigate to http://localhost:3000 to see the below website

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

Now click the "Show Toasts" button to see toast messages

toastify npm (How It Works For Developers): Figure 5 - After clicking on Show Toasts button, the application displays toast notifications for Success, Warning ad Error messages. Further you can use the text-field to enter the URL of the web page you want to convert into a PDF document and click on the "Generate PDF" button. This will convert the specified web page to a PDF using IronPDF.

Now Enter website URL to generate PDF and click generate PDF. A file named awesomeIron.pdf as below will be downloaded.

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

IronPDF License

IronPDF page.

Place the License Key in the app as shown below:

import {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 for adding toast notifications to your React applications. With its wide range of features and customization options, you can enhance the user experience by providing real-time feedback in a super easy and non-intrusive manner. On the other hand IronPDF is by far the most versatile enterprise library with support 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 its capabilities.

For more information on getting started with IronPDF, please refer to their documentation page and code examples.

< PREVIOUS
replicate npm (How It Works For Developers)
NEXT >
Socket io node.js (How It Works For Developers)

Ready to get started? Version: 2024.12 just released

Free npm Install View Licenses >