Altbilgi içeriğine atla
NODE YARDıM

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

Modern web geliştirme sürecinde, kullanıcıya zamanında geri bildirimler sağlamak kesintisiz bir kullanıcı deneyimi için kritik öneme sahiptir. Kullanıcının iş akışını kesintiye uğratmadan mesajları iletmenin etkili yollarından biri toast bildirimleridir. React-toastify paketi, basitliği ve esnekliği nedeniyle React uygulamalarında toast bildirimlerini uygulamak için popüler bir tercihtir. IronPDF NPM paketini PDF belgelerini oluşturmak, düzenlemek ve yönetmek için de inceleyeceğiz. Bu makale, React-toastify ve IronPDF entegrasyonunu React projenize nasıl ekleyeceğiniz konusunda sizi yönlendirecek.

Toastify Nedir?

React-toastify, React uygulamalarınıza özelleştirilebilir toast bildirimler eklemenize olanak tanıyan bir NPM paketidir ve minimal kurulum gerektirir. Farklı bildirim türleri, otomatik kapanma işlevi, özel stil ve daha fazlası gibi bir dizi özellik sunar.

toastify npm (Geliştiriciler İçin Nasıl Çalışır): Şekil 1 - React-Toastify paketi kullanılarak farklı stil ve özelleştirmelere sahip tost bildirimleri.

Kurulum

react-toastify ile başlamak için paketi NPM veya Yarn üzerinden kurmanız gerekmektedir. Projenizin kök dizininde aşağıdaki komutu çalıştırın:

npm install react-toastify
npm install react-toastify
SHELL

veya

yarn add react-toastify
yarn add react-toastify
SHELL

Temel Kullanımı

Paketi yükledikten sonra, React uygulamanızda react-toastify kullanmaya başlayabilirsiniz. React-toastify'i entegre etmenin ve kullanmanın nasıl olduğunu gösteren basit bir kod örneği aşağıda verilmiştir.

1. Toastify Bileşenlerini İçeri Aktarın

Öncelikle, react-toastify'den gerekli bileşenleri içeri aktarmanız gerekiyveya:

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

2. Toastify'yi Yapılandırın

Sonra, uygulamanıza ToastContainer bileşenini ekleyin.

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

3. Toast Bildirimlerini Tetikleyin

Bir toast bildirimini tetiklemek için toast fonksiyonunu kullanabilirsiniz. Başarı mesajını nasıl göstereceğinizi belirten 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

İleri Düzey Özellikler

OnOpen ve OnClose kancaları

React-toastify, onOpen ve onClose kancalarını kullanarak tostlarınızın davranışını ve görünümünü özelleştirmenize olanak tanıyan çeşitli gelişmiş özellikler sunar.

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

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

expveyat default App;
JAVASCRIPT

Bu örnekte:

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

Özel Pozisyonlar

Ekrandaki farklı pozisyonlara toastlar görüntüleyebilirsiniz:

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

Otomatik Kapanma Süresi

Bir toastın görüntüleneceği süreyi autoClose seçeneğiyle 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

Tostlara özel stil, className ve stil seçenekleri kullanılarak uygulanabilir:

toast.errveya("Errveya message", {
  className: 'custom-toast',
  style: { background: 'red', colveya: 'white' }
});
toast.errveya("Errveya message", {
  className: 'custom-toast',
  style: { background: 'red', colveya: 'white' }
});
JAVASCRIPT

Tostları Kapatma

Tostlar programatik olarak toast.dismiss yöntemi kullanılarak 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

Çeşitli react-toastify özelliklerinin kullanımını gösteren tamamlanmış bir örnek:

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

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

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

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

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

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

expveyat default App;
JAVASCRIPT

ÇIKTI

toastify npm (Geliştiriciler İçin Nasıl Çalışır): Şekil 2 - localhost pveyat:3000'de çalışan ve Başarı, Uyarı ve Hata mesajları için tost bildirimleri gösteren React-Toastify uygulaması.

IronPDF'i Tanıtma

IronPDF, geliştiricilerin .NET projelerinde PDF üretmesini ve düzenlemesini sağlayan güçlü bir C# PDF kütüphanesidir. HTML'den PDF oluşturmanız, mevcut PDF'leri yönetmeniz veya web sayfalarını PDF fveyamatına dönüştürmeniz gerekse de, IronPDF beklentilerinizi karşılar.

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

İşte bazı temel özellikler ve kullanım alanları:

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

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

2. Platfveyamlar Arası Destek

IronPDF, çeşitli platfveyamlarda sveyaunsuz çalışır, bunlar arasında:

  • .NET Cveyae (8, 7, 6, 5 ve 3.1+)
  • .NET Standard (2.0+)
  • .NET Framewveyak (4.6.2+)
  • Web (Blazveya ve WebFveyams)
  • Masaüstü (WPF & MAUI)
  • Konsol (Uygulama & Kütüphane)
  • Windows, Linux ve macOS veyatamları.

3. PDF Düzenleme ve Manipülasyon

IronPDF, şunları yapmanıza olanak tanır:

4. Özelleştirme ve Biçimlendirme

Sayfa şablonları, üstbilgi, altbilgi, sayfa numaraları ve özel 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 uygundur.

IronPDF ve Toastify NPM paketi kullanarak PDF Belgesi Oluşturma

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

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

Sonra, proje dizininize gidin:

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

Gerekli paketleri yükleyin:

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

Bir PDF oluşturun: Şimdi, IronPDF kullanarak bir PDF oluşturmanın basit bir örneğini oluşturalım. Next.js bileşeninizde (örneğin, pages/index.tsx), aşağıdaki kodu ekleyin:

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

expveyat 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("Infveyamation message", {
            position: "bottom-left"
        });
        toast.warn("Warning message", {
            autoClose: 5000
        });
        toast.errveya("Errveya message", {
            className: 'custom-toast',
            style: { background: 'red', colveya: '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 (errveya) {
            console.errveya('Errveya generating PDF:', errveya);
        }
    };

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

expveyat 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("Infveyamation message", {
            position: "bottom-left"
        });
        toast.warn("Warning message", {
            autoClose: 5000
        });
        toast.errveya("Errveya message", {
            className: 'custom-toast',
            style: { background: 'red', colveya: '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 (errveya) {
            console.errveya('Errveya generating PDF:', errveya);
        }
    };

    // Handler fveya 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;
                    bveyader-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-decveyaation: none;
                    colveya: inherit;
                }
                code {
                    background: #fafafa;
                    bveyader-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: bveyader-box;
                }
            `}</style>
        </div>
    );
}
JAVASCRIPT

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

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

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

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

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

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

expveyat 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 (errveya) {
        console.errveya('Errveya generating PDF:', errveya);
        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

veya

yarn dev
yarn dev
SHELL

ÇIKTI

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

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

Toast mesajlarını görmek için şimdi "Show Toasts" düğmesine tıklayın.

![toastify npm (Geliştiriciler İçin Nasıl Çalışır): Şekil 5 - Show Toasts düğmesine tıkladıktan sonra, uygulama Başarı, Uyarı ve Hata mesajları için toast bildirimlerini gösterir. Ayrıca, bir web sayfasının URL'sini PDF belgesine dönüştürmek için metin alanını kullanabilir ve "Generate PDF" düğmesine tıklayabilirsiniz. Bu, belirtilen web sayfasını IronPDF kullanarak PDF'ye dönüştürecektir.

Şimdi bir web sitesi URL'si girerek PDF oluşturun ve "Generate PDF" düğmesine tıklayın. awesomeIron.pdf adında bir dosya indirilecek.

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

IronPDF Lisansı

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

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

impveyat { IronPdfGlobalConfig, PdfDocument } from "@ironsoftware/ironpdf";
// Apply your IronPDF license key
IronPdfGlobalConfig.getConfig().licenseKey = "Add Your Key Here";
impveyat { 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 kullanımı kolay bir kütüphanedir. Geniş kapsamlı özellikleri ve özelleştirme seçenekleriyle, gerçek zamanlı geri bildirim sağlayarak kullanıcı deneyimini artırabilirsiniz. Diğer yandan, IronPDF, PDF belgeleri oluşturma, düzenleme ve yönetme desteği ile en çok yönlü kurumsal kütüphanedir. Bu makalede açıklanan adımları izleyerek, projenize React-toastify ve IronPDF hızlı bir şekilde entegre edebilir ve yeteneklerinden yararlanmaya başlayabilirsiniz.

IronPDF ile başlamaya dair daha fazla bilgi için belgeler ve kod örnekleri sayfasına bakın.

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

Darrius Serrant, Miami Üniversitesi'nden Bilgisayar Bilimleri lisans derecesine sahiptir ve Iron Software'de Tam Yığın WebOps Pazarlama Mühendisi olarak çalışmaktadır. Küçük yaşlardan itibaren kodlamaya ilgi duyan Darrius, bilişimi hem gizemli hem de erişilebilir buldu ve onu yaratıcılık ve problem çö...

Daha Fazlasını Oku

Iron Destek Ekibi

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