Altbilgi içeriğine atla
NODE YARDıM

toastify npm (Geliştiriciler İçin Nasıl Çalışır)

Modern web geliştirmede, kullanıcılara zamanında geri bildirim sağlamak, kesintisiz bir kullanıcı deneyimi için çok önemlidir. Toast bildirimleri, kullanıcıların iş akışını bozmadan mesajlar iletmenin etkili bir yoludur. React-toastify paketi, React uygulamalarında toast bildirimlerini uygulanması için basitliği ve esnekliği nedeniyle popüler bir seçimdir. IronPDF NPM paketine PDF belgeleri oluşturmak, düzenlemek ve yönetmek için bakacağız. Bu makale, projeinizde React-toastify ve IronPDF entegrasyon sürecinde size rehberlik edecektir.

Toastify nedir?

React-toastify, React uygulamalarınıza özelleştirilebilir toast bildirimleri eklemenizi minimal kurulum ile sağlayan bir NPM paketidir. Farklı bildirim türleri, otomatik kapatma işlevi, özel stil ve daha fazlası gibi bir dizi özellik sunar.

toastify npm (Geliştiriciler için Nasıl Çalışır): Şekil 1 - React-Toastify paketi kullanılarak farklı stillerde ve özelleştirmelerle toast bildirimleri.

Kurulum

react-toastify ile başlamak için, paketi NPM veya Yarn ile kurmalısınız. Projelerinizin kök dizininde aşağıdaki komutu çalıştırın:

npm install react-toastify
npm install react-toastify
SHELL

or

yarn add react-toastify
yarn add react-toastify
SHELL

Temel Kullanım

Paketi kurduktan sonra, React uygulamanızda react-toastify kullanmaya başlayabilirsiniz. Aşağıda, react-toastify'ı entegre etmek ve kullanmak için basit bir kod örneği verilmiştir.

1. Toastify Bileşenlerini İçe Aktarma

Önce, react-toastify'dan gerekli bileşenleri içe aktarmanız gerekir:

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

2. Toastify'i Yapılandırma

Sonra, ToastContainer bileşenini uygulamanıza ekleyin.

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

3. Toast Bildirimlerini Tetikleme

toast fonksiyonunu kullanarak bir toast bildirimi tetikleyebilirsiniz. İşte başarı mesajı gösterimi için bir kod örneği:

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

Gelişmiş Özellikler

OnOpen ve OnClose kancaları

React-toastify, onOpen ve onClose kancaları kullanarak toast'larınızın davranışını ve görünümünü özelleştirmenizi sağlayan çeşitli gelişmiş özellikler sunar.

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;
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

Bu örnekte:

  • Toast açıldığında, onOpen kancası tetiklenir ve bir uyarı gösterilir.
  • Toast kapandığında, onClose kancası tetiklenir ve başka bir uyarı gösterilir.

Özel Pozisyonlar

Toasts ekranın farklı bölgelerinde position seçeneği kullanılarak gösterilebilir:

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

Otomatik Kapatma Süresi

Bir toast'un ekranda ne kadar süre gösterileceğini autoClose seçeneği ile ayarlayabilirsiniz:

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

Özel Stil

Toasts için özel stil, className ve style seçenekleri kullanılarak uygulanabilir.

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

Toasts'u Kapatma

Toasts, toast.dismiss yöntemi kullanılarak programatik olarak kapatılabilir.

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'ın çeşitli özelliklerinin kullanımını gösteren tam bir örnek aşağıda verilmiştir:

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"
    });
    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' }
    });
  };

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

export default App;
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"
    });
    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' }
    });
  };

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

export default App;
JAVASCRIPT

ÇIKTI

toastify npm (Geliştiriciler için Nasıl Çalışır): Şekil 2 - React-Toastify uygulaması, localhost port:3000'de çalışıyor ve Başarı, Uyarı ve Hata mesajları için toast bildirimlerini gösteriyor.

IronPDF Tanıtımı

IronPDF, geliştiricilere .NET projelerinde PDF oluşturma ve düzenleme olanağı sağlayan güçlü bir C# PDF kütüphanesidir. İster HTML'den PDF oluşturmanız gerekse mevcut PDF'leri manipüle etmeniz veya web sayfalarını PDF formatına çevirmeniz gerektiğinde, IronPDF her ihtiyacınızı karşılar.

toastify npm (Geliştiriciler için Nasıl Çalışır): Şekil 3 - IronPDF for Node.js: Node.js PDF Kütüphanesi

İşte bazı ana özellikler ve kullanım durumları:

1. HTML'den PDF'ye Dönüştürme

IronPDF, URL'den, HTML dosyasından veya HTML dizisinden gelen HTML sayfalarını PDF'ye dönüştürebilir. Yerel HTML dosyalarını veya HTML dizilerini PDF'ye de dönüştürebilirsiniz.

2. Çapraz-Platform Desteği

IronPDF, aşağıdakiler dahil çeşitli platformlarda sorunsuz çalışır:

  • .NET Core (8, 7, 6, 5 ve 3.1+)
  • .NET Standard (2.0+)
  • .NET Framework (4.6.2+)
  • Web (Blazor & WebForms)
  • Masaüstü (WPF & MAUI)
  • Konsol (Uygulama & Kütüphane)
  • Windows, Linux ve macOS ortamları.

3. PDF'leri Düzenleme ve Manipüle Etme

IronPDF, aşağıdakileri yapmanıza olanak tanır:

4. Özelleştirme ve Biçimlendirme

Sayfa şablonları, başlıklar, altbilgiler, sayfa numaraları ve özel sayfa kenar boşlukları uygulayabilirsiniz. IronPDF, UTF-8 karakter kodlaması, temel URL'ler, varlık kodlaması ve daha fazlasını destekler.

5. Standartlara Uygunluk

IronPDF, PDF sürümleri (1.2 - 1.7), PDF/UA (PDF/UA-1) ve PDF/A (PDF/A-3b) dahil olmak üzere çeşitli PDF standartlarına uyar.

IronPDF ve Toastify NPM paketi kullanarak PDF Belgesi Oluşturma

Bağımlılıkları Kurun: İlk olarak, aşağıdaki komutu kullanarak yeni bir Next.js projesi oluşturun (henüz yapmadıysanız). Lütfen kurulum sayfasına bakınız.

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

Sonrasında, proje dizinine gidin:

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

Gerekli paketleri kurun:

npm install @ironsoftware/ironpdf, react-toastify

PDF Oluştur: Şimdi, IronPDF kullanarak PDF oluşturma işleminin basit bir örneğini yapalım. Next.js bileşeninizde (ör. pages/index.tsx) aşağıdaki kodu ekleyin:

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('');

    // Function to show toast notifications
    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' }
        });
    };

    // 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 (error) {
            console.error('Error generating PDF:', error);
        }
    };

    // Handler for 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;
                    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>
    );
}
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('');

    // Function to show toast notifications
    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' }
        });
    };

    // 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 (error) {
            console.error('Error generating PDF:', error);
        }
    };

    // Handler for 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;
                    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

IronPDF yalnızca Node.js üzerinde çalıştığı için, PDF'nin Node.js kullanılarak oluşturulduğu bir API uygulaması için ekleyin.

pages/api klasöründe pdf.js adlı bir dosya oluşturun ve aşağıdaki kodu ekleyin:

// 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.log('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();
    }
}
// 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.log('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

Not: Yukarıdaki koda kendi lisans anahtarınızı ekleyin.

Uygulamanızı Çalıştırın: Next.js uygulamanızı başlatın:

npm run dev
npm run dev
SHELL

or

yarn dev
yarn dev
SHELL

ÇIKTI

Tarayıcıyı açın ve aşağıdaki web sitesini görmek için http://localhost:3000 adresine gidin:

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.

Toast mesajlarını görmek için şimdi "Show Toasts" butonuna tıklayın.

! [toastify npm (Geliştiriciler İçin Nasıl Çalışır): Şekil 5 - Show Toasts butonuna tıklandıktan sonra, uygulama Başarı, Uyarı ve Hata mesajları için toast bildirimlerini gösterir. URL'sini PDF belgesine dönüştürmek istediğiniz web sayfasının URL'sini yazmak için metin alanını kullanabilir ve "Generate PDF" butonuna tıklayabilirsiniz. Bu, belirtilen web sayfasını IronPDF kullanarak PDF'ye dönüştürecektir.] (/static-assets/pdf/blog/toastify-npm/toastify-npm-5.webp)

PDF oluşturmak için şimdi bir web sitesi URL'si girin ve "Generate PDF" seçeneğine tıklayın. awesomeIron.pdf adlı bir dosya indirilecektir.

toastify npm (Geliştiriciler için Nasıl Çalışır): Şekil 6 - Belirtilen URL'yi PDF'e dönüştürerek oluşturulan çıktı PDF IronPDF kullanılarak

IronPDF Lisansı

IronPDF lisansı hakkında bilgi için lütfen IronPDF Lisansı sayfasına bakınız.

Lisans Anahtarını aşağıda gösterildiği gibi uygulamaya yerleştirin:

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

Sonuç

React-toastify, React uygulamalarınıza toast bildirimleri eklemek için güçlü ve kolay kullanımlı bir kütüphanedir. Geniş özellik seçenekleri ve özelleştirme seçenekleri ile kullanıcı deneyimini klasik bir şekilde ve müdahaleci olmayan bir şekilde artırabilirsiniz. Öte yandan, IronPDF, PDF belgeleri oluşturma, düzenleme ve yönetme desteğiyle en çok yönlü kurumsal kütüphanedir. Bu makalede açıklanan adımları izleyerek, React-toastify ve IronPDF projenize hızlı bir şekilde entegre edebilir ve yeteneklerinden yararlanmaya başlayabilirsiniz.

IronPDF ile çalışmaya başlamak için daha fazla bilgi için, dokümantasyon sayfasına ve kod örnekleri sayfasına bakınız.

Darrius Serrant
Tam Yığın Yazılım Mühendisi (WebOps)

Darrius Serrant, Miami Üniversitesi'nden Bilgisayar Bilimi alanında Lisans Derecesine sahip ve Iron Software'de Tam Yığın WebOps Pazarlama Mühendisi olarak çalışıyor. Genç yaşlardan itibaren kodlamaya çekildi, bilgisayar bilimi hem gizemli hem de erişilebilir olarak görüldü ve bu özellik, yaratıcılık ...

Daha Fazla Oku

Iron Destek Ekibi

Haftada 5 gün, 24 saat çevrimiçiyiz.
Sohbet
E-posta
Beni Ara