푸터 콘텐츠로 바로가기
노드 도움말

Toastify npm 사용법 (개발자를 위한 작동 방식)

현대 웹 개발에서 사용자에게 시의적절한 피드백을 제공하는 것은 원활한 사용자 경험을 위해 매우 중요합니다. 토스트 알림은 사용자의 작업 흐름을 방해하지 않고 메시지를 전달하는 효과적인 방법입니다. React-toastify 패키지는 간편하고 유연하기 때문에 React 애플리케이션에서 토스트 알림을 구현하는 데 널리 사용됩니다. 또한 PDF 문서를 생성, 편집 및 관리하기 위한 IronPDF NPM 패키지에 대해서도 살펴보겠습니다. 이 글에서는 React-toastifyIronPDF React 프로젝트에 통합하는 과정을 안내합니다.

Toastify란 무엇인가요?

React-toastify 는 최소한의 설정만으로 React 애플리케이션에 사용자 정의 가능한 토스트 알림을 추가할 수 있는 NPM 패키지입니다. 다양한 알림 유형, 자동 닫기 기능, 사용자 정의 스타일 지정 등 다양한 기능을 제공합니다.

toastify npm (개발자를 위한 작동 방식): 그림 1 - React-Toastify 패키지를 사용하여 다양한 스타일과 사용자 지정으로 제공되는 토스트 알림.

설치

react-toastify를 사용하려면 NPM 또는 Yarn을 통해 패키지를 설치해야 합니다. 프로젝트의 루트 디렉토리에서 다음 명령어를 실행하세요.

npm install react-toastify
npm install react-toastify
SHELL

또는

yarn add react-toastify
yarn add react-toastify
SHELL

기본 사용법

패키지를 설치한 후에는 React 애플리케이션에서 react-toastify를 사용할 수 있습니다. 다음은 react-toastify를 통합하고 사용하는 방법을 보여주는 간단한 코드 예제입니다.

1. Toastify 구성 요소 가져오기

먼저 react-toastify에서 필요한 구성 요소를 가져와야 합니다.

imp또는t React from 'react';
imp또는t { ToastContainer, toast } from 'react-toastify';
imp또는t 'react-toastify/dist/ReactToastify.css';
imp또는t React from 'react';
imp또는t { ToastContainer, toast } from 'react-toastify';
imp또는t 'react-toastify/dist/ReactToastify.css';
JAVASCRIPT

2. Toastify 설정

다음으로, 애플리케이션에 ToastContainer 컴포넌트를 추가하세요.

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

3. 토스트 알림 실행

toast 함수를 사용하면 토스트 알림을 표시할 수 있습니다. 다음은 성공 메시지를 표시하는 코드 예시입니다.

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

고급 기능

OnOpenOnClose

React-toastify는 onOpenonClose 훅을 사용하여 토스트의 동작과 모양을 사용자 지정할 수 있는 다양한 고급 기능을 제공합니다.

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

exp또는t default App;
imp또는t React from 'react';
imp또는t { ToastContainer, toast } from 'react-toastify';
imp또는t '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>
  );
}

exp또는t default App;
JAVASCRIPT

이 예시에서는 다음과 같습니다.

토스트 메시지가 열리면 onOpen 훅이 트리거되어 알림창이 표시됩니다. 토스트 메시지가 닫히면 onClose 훅이 실행되어 다른 알림이 표시됩니다.

사용자 지정 위치

위치 옵션을 사용하면 화면의 여러 위치에 토스트 메시지를 표시할 수 있습니다.

toast.info("Inf또는mation message", {
  position: "top-right"
});
toast.info("Inf또는mation message", {
  position: "top-right"
});
JAVASCRIPT

자동 닫기 지속 시간

autoClose 옵션을 사용하면 토스트 메시지가 표시되는 시간을 설정할 수 있습니다.

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

맞춤 스타일링

className 및 style 옵션을 사용하여 토스트에 사용자 지정 스타일을 적용할 수 있습니다.

toast.err또는("Err또는 message", {
  className: 'custom-toast',
  style: { background: 'red', col또는: 'white' }
});
toast.err또는("Err또는 message", {
  className: 'custom-toast',
  style: { background: 'red', col또는: 'white' }
});
JAVASCRIPT

건배를 거부하다

토스트 메시지는 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

다음은 react-toastify의 다양한 기능을 사용하는 방법을 보여주는 전체 예제입니다.

imp또는t React from 'react';
imp또는t { ToastContainer, toast } from 'react-toastify';
imp또는t 'react-toastify/dist/ReactToastify.css';

function App() {
  const notify = () => {
    toast.success("Success! This is a success message.", {
      position: "top-right"
    });
    toast.info("Inf또는mation message", {
      position: "bottom-left"
    });
    toast.warn("Warning message", {
      autoClose: 5000
    });
    toast.err또는("Err또는 message", {
      className: 'custom-toast',
      style: { background: 'red', col또는: 'white' }
    });
  };

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

exp또는t default App;
imp또는t React from 'react';
imp또는t { ToastContainer, toast } from 'react-toastify';
imp또는t 'react-toastify/dist/ReactToastify.css';

function App() {
  const notify = () => {
    toast.success("Success! This is a success message.", {
      position: "top-right"
    });
    toast.info("Inf또는mation message", {
      position: "bottom-left"
    });
    toast.warn("Warning message", {
      autoClose: 5000
    });
    toast.err또는("Err또는 message", {
      className: 'custom-toast',
      style: { background: 'red', col또는: 'white' }
    });
  };

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

exp또는t default App;
JAVASCRIPT

출력

toastify npm (개발자를 위한 작동 방식): 그림 2 - localhost 포트:3000에서 실행 중인 React-Toastify 애플리케이션이며 성공, 경고, 오류 메시지에 대한 토스트 알림을 표시합니다.

IronPDF 소개합니다

IronPDF 개발자가 .NET 프로젝트에서 PDF를 생성하고 편집할 수 있도록 해주는 강력한 C# PDF 라이브러리입니다. HTML에서 PDF를 생성하거나, 기존 PDF를 수정하거나, 웹 페이지를 PDF 형식으로 변환해야 하는 경우 IronPDF 모든 것을 해결해 드립니다.

toastify npm (개발자를 위한 작동 방식): 그림 3 - IronPDF f또는 Node.js: Node.js PDF 라이브러리

다음은 몇 가지 주요 기능과 사용 사례입니다.

1. HTML을 PDF로 변환

IronPDF URL, HTML 파일 또는 HTML 문자열 등 어떤 형태의 HTML 페이지든 PDF로 변환할 수 있습니다. 로컬 HTML 파일이나 HTML 문자열을 PDF로 변환할 수도 있습니다.

2. 크로스 플랫폼 지원

IronPDF 다음과 같은 다양한 플랫폼에서 원활하게 작동합니다.

  • .NET C또는e (8, 7, 6, 5 및 3.1 이상)
  • .NET Standard (2.0 이상)
  • .NET Framew또는k (4.6.2 이상)
  • 웹 (Blaz또는 및 웹폼)
  • 데스크톱 (WPF 및 MAUI)
  • 콘솔(앱 및 라이브러리)
  • 윈도우, 리눅스, macOS 환경.

3. PDF 편집 및 조작

IronPDF 사용하면 다음과 같은 작업을 수행할 수 있습니다.

4. 사용자 지정 및 서식 지정

페이지 템플릿, 머리글, 바닥글, 페이지 번호 및 사용자 지정 여백을 적용할 수 있습니다. IronPDF UTF-8 문자 인코딩, 기본 URL, 자산 인코딩 등을 지원합니다.

5. 표준 준수

IronPDF PDF 버전(1.2~1.7), PDF/UA(PDF/UA-1), PDF/A(PDF/A-3b)를 포함한 다양한 PDF 표준을 준수합니다.

IronPDF 와 Toastify NPM 패키지를 사용하여 PDF 문서 생성

필수 구성 요소 설치: 먼저 다음 명령어를 사용하여 새 Next.js 프로젝트를 생성합니다(아직 생성하지 않은 경우). 설정 페이지를 참조하십시오.

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

다음으로 프로젝트 디렉토리로 이동하세요.

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

필요한 패키지를 설치하세요:

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

PDF 생성: 이제 IronPDF 사용하여 간단한 PDF 생성 예제를 만들어 보겠습니다. Next.js 컴포넌트(예: pages/index.tsx)에 다음 코드를 추가하세요.

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

exp또는t 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("Inf또는mation message", {
            position: "bottom-left"
        });
        toast.warn("Warning message", {
            autoClose: 5000
        });
        toast.err또는("Err또는 message", {
            className: 'custom-toast',
            style: { background: 'red', col또는: '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 (err또는) {
            console.err또는('Err또는 generating PDF:', err또는);
        }
    };

    // Handler f또는 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;
                    b또는der-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-dec또는ation: none;
                    col또는: inherit;
                }
                code {
                    background: #fafafa;
                    b또는der-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: b또는der-box;
                }
            `}</style>
        </div>
    );
}
imp또는t Head from 'next/head';
imp또는t styles from '../styles/Home.module.css';
imp또는t { ToastContainer, toast } from 'react-toastify';
imp또는t 'react-toastify/dist/ReactToastify.css';
imp또는t { useState } from "react";

exp또는t 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("Inf또는mation message", {
            position: "bottom-left"
        });
        toast.warn("Warning message", {
            autoClose: 5000
        });
        toast.err또는("Err또는 message", {
            className: 'custom-toast',
            style: { background: 'red', col또는: '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 (err또는) {
            console.err또는('Err또는 generating PDF:', err또는);
        }
    };

    // Handler f또는 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;
                    b또는der-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-dec또는ation: none;
                    col또는: inherit;
                }
                code {
                    background: #fafafa;
                    b또는der-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: b또는der-box;
                }
            `}</style>
        </div>
    );
}
JAVASCRIPT

IronPDF Node.js 에서만 실행되므로, 다음으로 Node.js 사용하여 PDF를 생성하는 앱용 API를 추가해야 합니다.

아래 코드를 추가하여 pages/api 폴더에 pdf.js 파일을 만드세요:

// pages/api/pdf.js
imp또는t { IronPdfGlobalConfig, PdfDocument } from "@ironsoftware/ironpdf";

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

exp또는t 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 (err또는) {
        console.err또는('Err또는 generating PDF:', err또는);
        res.status(500).end();
    }
}
// pages/api/pdf.js
imp또는t { IronPdfGlobalConfig, PdfDocument } from "@ironsoftware/ironpdf";

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

exp또는t 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 (err또는) {
        console.err또는('Err또는 generating PDF:', err또는);
        res.status(500).end();
    }
}
JAVASCRIPT

참고: 위 코드에 사용자 고유의 라이선스 키를 추가하십시오.

앱 실행하기: Next.js 앱을 시작하세요:

npm run dev
npm run dev
SHELL

또는

yarn dev
yarn dev
SHELL

출력

브라우저를 열고 http://localhost:3000으로 이동하면 아래 웹사이트를 볼 수 있습니다.

toastify npm (How It W또는ks F또는 Developers): Figure 4 - React-Toastify application running on localhost p또는t:3000 and displaying a button Show Toasts, along with a text-field f또는 Enter URL To Convert to PDF and a Generate PDF button.

이제 "알림 메시지 보기" 버튼을 클릭하여 알림 메시지를 확인하세요.

toastify npm (개발자를 위한 작동 방식): 그림 5 - '토스트 표시' 버튼을 클릭하면 애플리케이션이 성공, 경고 및 오류 메시지에 대한 토스트 알림을 표시합니다. 또한 텍스트 필드에 PDF 문서로 변환하려는 웹 페이지의 URL을 입력하고 PDF 생성 버튼을 클릭할 수 있습니다. 이 명령은 IronPDF 사용하여 지정된 웹 페이지를 PDF로 변환합니다.

이제 PDF를 생성할 웹사이트 URL을 입력하고 "PDF 생성"을 클릭하세요. awesomeIron.pdf로 이름이 지정된 파일이 다운로드됩니다.

toastify npm (개발자를 위한 작동 방식): 그림 6 - IronPDF를 사용하여 지정된 URL을 PDF로 변환하여 생성된 출력 PDF

IronPDF 라이선스

IronPDF 라이선스에 대한 자세한 내용은 IronPDF 라이선스 페이지를 참조하십시오.

아래 그림과 같이 앱에 라이선스 키를 입력하십시오.

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

결론

React-toastify 는 React 애플리케이션에 토스트 알림을 추가하는 강력하고 사용하기 쉬운 라이브러리입니다. 다양한 기능과 맞춤 설정 옵션을 통해 매우 간편하고 방해받지 않는 방식으로 실시간 피드백을 제공하여 사용자 경험을 향상시킬 수 있습니다. 반면 IronPDF PDF 문서 생성, 편집 및 관리를 지원하는 가장 다재다능한 기업용 라이브러리입니다. 이 문서에 설명된 단계를 따르면 React-toastifyIronPDF 프로젝트에 빠르게 통합하고 해당 기능을 활용할 수 있습니다.

IronPDF 시작하기에 대한 자세한 내용은 IronPDF 문서 페이지와 코드 예제를 참조하십시오.

다리우스 세란트
풀스택 소프트웨어 엔지니어 (웹 운영)

다리우스 세런트는 마이애미 대학교에서 컴퓨터 과학 학사 학위를 받았으며, Iron Software에서 풀 스택 웹 운영 마케팅 엔지니어로 근무하고 있습니다. 어린 시절부터 코딩에 매료되었던 그는 컴퓨팅이 신비로우면서도 접근하기 쉬운 분야라고 생각했고, 창의력과 문제 해결 능력을 발휘하기에 완벽한 매체라고 여겼습니다.

Iron Software에서 다리우스는 새로운 것을 만들고 복잡한 개념을 단순화하여 더 쉽게 이해할 수 있도록 하는 것을 즐깁니다. 그는 사내 개발자로서 학생들을 가르치는 데에도 자원하여 차세대 인재들과 전문 지식을 공유하고 있습니다.

다리우스에게 있어 그의 일은 가치 있고 실질적인 영향을 미치기 때문에 보람 있는 일입니다.

아이언 서포트 팀

저희는 주 5일, 24시간 온라인으로 운영합니다.
채팅
이메일
전화해