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

linkify-react (작동 방식: 개발자 가이드)

웹 개발이라는 광범위한 분야에서 텍스트 내에 클릭 가능한 링크 또는 앵커 태그를 만드는 것은 기본적인 작업입니다. 블로그, 소셜 미디어 플랫폼 또는 이메일 클라이언트를 구축하든 관계없이 URL, 이메일 주소 및 기타 텍스트를 자동으로 감지하고 클릭 가능한 링크로 변환하는 기능은 원활한 사용자 경험을 제공하는 데 매우 중요합니다. Linkify React는 React 애플리케이션에서 이러한 프로세스를 간소화하도록 설계된 강력한 npm 패키지입니다. 이 글에서는 Linkify를 사용하여 React 프로젝트에서 링크 생성을 간소화하는 방법을 코드 예제와 함께 살펴보겠습니다.

이와 더불어 웹 페이지에서 고품질 PDF 문서를 생성할 수 있는 다재다능한 라이브러리인 IronPDF 도 소개해 드리겠습니다. IronPDF 와 Linkify를 함께 사용하면 Linkify에서 식별하고 변환한 클릭 가능한 링크를 그대로 유지하는 PDF를 쉽게 만들 수 있으며, 이를 통해 문서가 웹 콘텐츠와 동일한 상호 작용성을 유지하도록 보장할 수 있음을 보여드리겠습니다.

Linkify React 컴포넌트 시작하기

Linkify React는 URL, 이메일 주소 및 자식 문자열 내에 발견된 기타 링크를 포함하는 일반 텍스트를 중첩 요소 형태의 클릭 가능한 하이퍼링크로 자동 변환하는 가볍고 사용하기 쉬운 npm 패키지입니다. 이를 통해 수동 링크 구문 분석 및 서식 지정이 필요 없어지므로 개발자의 귀중한 시간과 노력을 절약할 수 있습니다. Linkify를 React 애플리케이션에 통합하는 방법을 자세히 살펴보겠습니다.

설치

React Linkify를 사용하려면 먼저 프로젝트에 종속성으로 설치해야 합니다. npm이나 yarn을 사용하면 이 작업을 수행할 수 있습니다. 터미널을 열고 다음 명령어를 실행하세요.

npm install react-linkify
# or
yarn add react-linkify
npm install react-linkify
# or
yarn add react-linkify
SHELL

용법

React Linkify를 설치하면 React 컴포넌트에 쉽게 통합할 수 있습니다. 다음은 React Linkify를 사용하여 텍스트 콘텐츠 내에 클릭 가능한 링크를 렌더링하는 방법을 보여주는 간단한 예입니다.

import React from 'react';
import Linkify from 'react-linkify';

// A React component to display clickable links
const MyComponent = () => {
  return (
    <div>
      <h1>Clickable Links with React Linkify</h1>
      <Linkify>
        <p>
          Check out this cool website: https://example.com
          <br />
          You can also reach me at hello@example.com
        </p>
      </Linkify>
    </div>
  );
};

export default MyComponent;
import React from 'react';
import Linkify from 'react-linkify';

// A React component to display clickable links
const MyComponent = () => {
  return (
    <div>
      <h1>Clickable Links with React Linkify</h1>
      <Linkify>
        <p>
          Check out this cool website: https://example.com
          <br />
          You can also reach me at hello@example.com
        </p>
      </Linkify>
    </div>
  );
};

export default MyComponent;
JAVASCRIPT

이 예에서, 우리는 react-linkify 패키지에서 Linkify 구성 요소를 가져와서 우리의 텍스트 내용을 그것 안에 감쌉니다. React Linkify는 텍스트 내의 URL과 이메일 주소를 자동으로 감지하여 클릭 가능한 하이퍼링크로 변환합니다.

맞춤 설정

Linkify는 생성된 링크의 동작과 모양을 사용자 지정할 수 있는 다양한 속성, 특성 및 옵션을 제공합니다. 예를 들어, 링크가 열리는 방식을 제어하기 위해 target 속성을 지정할 수 있습니다. React Linkify의 동작을 사용자 지정하는 방법은 다음과 같습니다.

<Linkify properties={{ target: '_blank' }}>
  <p>
    Clickable links will open in a new tab: https://example.com
  </p>
</Linkify>
<Linkify properties={{ target: '_blank' }}>
  <p>
    Clickable links will open in a new tab: https://example.com
  </p>
</Linkify>
JAVASCRIPT

IronPDF 소개합니다

IronPDF 는 Node.js 애플리케이션 내에서 PDF 생성을 용이하게 하도록 설계된 강력한 npm 패키지입니다. 이 기능을 사용하면 HTML 콘텐츠 , URL 또는 기존 PDF 파일에서 PDF 문서를 생성할 수 있습니다. IronPDF 직관적인 API 와 강력한 기능 세트를 통해 송장, 보고서 또는 기타 모든 유형의 문서를 생성하는 과정을 간소화합니다.

linkify-react (작동 방식: 개발자를 위한 안내서): 그림 1 - IronPDF for Node.js: Node.js PDF 라이브러리 웹사이트

IronPDF 의 주요 기능은 다음과 같습니다.

1. HTML을 PDF로 변환

HTML 요소를 PDF 문서로 손쉽게 변환하세요. 이 기능은 웹 콘텐츠에서 동적 PDF를 생성하는 데 특히 유용합니다.

2. URL을 PDF로 변환

URL에서 바로 PDF 파일을 생성합니다. 이 기능을 사용하면 웹 페이지의 콘텐츠를 캡처하여 프로그램적으로 PDF 파일로 저장할 수 있습니다.

3. PDF 조작

기존 PDF 문서를 손쉽게 병합, 분할 및 편집하세요. IronPDF 페이지 추가, 문서 분할 등 PDF 파일을 조작할 수 있는 기능을 제공합니다.

4. PDF 보안

PDF 문서를 암호로 암호화하거나 디지털 서명을 적용하여 보안을 강화하세요. IronPDF 무단 접근으로부터 중요한 문서를 보호할 수 있는 다양한 옵션을 제공합니다.

5. 고품질 출력

텍스트, 이미지 및 서식이 정확하게 표현된 고품질 PDF 문서를 제작하세요. IronPDF 생성된 PDF 파일이 원본 콘텐츠와 동일한 품질을 유지하도록 보장합니다.

6. 크로스 플랫폼 호환성

IronPDF 는 Windows, Linux, macOS를 비롯한 다양한 플랫폼과 호환되므로 폭넓은 개발 환경에 적합합니다.

7. 간단한 적분

IronPDF의 npm 패키지를 사용하면 IronPDF Node.js 애플리케이션에 쉽게 통합할 수 있습니다. API 문서가 잘 되어 있어 프로젝트에 PDF 생성 기능을 쉽게 통합할 수 있습니다.

웹 애플리케이션, 서버 측 스크립트 또는 명령줄 도구를 개발하든 IronPDF 사용하면 전문가 수준의 PDF 문서를 효율적이고 안정적으로 생성할 수 있습니다.

IronPDF 와 Linkify React를 사용하여 PDF 문서를 생성하세요

설치 종속성

먼저, 다음 명령어를 사용하여 새 Next.js 프로젝트를 생성하세요(아직 생성하지 않았다면).

npx create-next-app@latest linkify-ironpdf --use-npm --example "https://github.com/vercel/next-learn/tree/main/basics/learn-starter"
npx create-next-app@latest linkify-ironpdf --use-npm --example "https://github.com/vercel/next-learn/tree/main/basics/learn-starter"
SHELL

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

cd linkify-ironpdf
cd linkify-ironpdf
SHELL

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

yarn add @ironsoftware/ironpdf @ironsoftware/ironpdf-engine-windows-x64
yarn add react-linkify
yarn add @ironsoftware/ironpdf @ironsoftware/ironpdf-engine-windows-x64
yarn add react-linkify
SHELL

PDF 생성

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

PDF 생성 API: 첫 번째 단계는 PDF 문서를 생성하는 백엔드 API를 만드는 것입니다. IronPDF 서버 측에서만 실행되므로 사용자가 PDF를 생성하고자 할 때 호출할 API를 만들어야 합니다. 경로 pages/api/pdf.js에 파일을 생성하고 아래 내용을 추가하십시오.

IronPDF 사용하려면 라이선스 키가 필요합니다. 라이선스 페이지 에서 라이선스 키를 받아 아래 코드에 붙여넣으면 됩니다.

// pages/api/pdf.js

import { IronPdfGlobalConfig, PdfDocument } from "@ironsoftware/ironpdf";

// Apply your IronPDF license key
IronPdfGlobalConfig.getConfig().licenseKey = "Your license key goes 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();
  }
}
// pages/api/pdf.js

import { IronPdfGlobalConfig, PdfDocument } from "@ironsoftware/ironpdf";

// Apply your IronPDF license key
IronPdfGlobalConfig.getConfig().licenseKey = "Your license key goes 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

아래는 사용자를 위한 PDF 생성 페이지를 설정하는 index.js 코드입니다.

import Head from "next/head";
import styles from "../styles/Home.module.css";
import React, { useState } from "react";
import Linkify from 'react-linkify';

// Home component for link conversion and PDF generation
export default function Home() {
  const [text, setText] = useState("");

  // Function to generate PDF from entered URL
  const generatePdf = async () => {
    try {
      const response = await fetch("/api/pdf?url=" + text);
      const blob = await response.blob();
      const url = window.URL.createObjectURL(new Blob([blob]));
      const link = document.createElement("a");
      link.href = url;
      link.setAttribute("download", "awesomeIron.pdf");
      document.body.appendChild(link);
      link.click();
      link.parentNode.removeChild(link);
    } catch (error) {
      console.error("Error generating PDF:", error);
    }
  };

  // Handle changes in the input text field
  const handleChange = (event) => {
    setText(event.target.value);
  };

  return (
    <div className={styles.container}>
      <Head>
        <title>Generate PDF Using IronPDF</title>
        <link rel="icon" href="/favicon.ico" />
      </Head>
      <main>
        <h1>Demo Linkify and Generate PDF Using IronPDF</h1>
        <p>
          <span>Enter URL to Linkify and Convert to PDF:</span>{" "}
        </p>
        <input type="text" value={text} onChange={handleChange} />
        <Linkify properties={{ target: '_blank' }}>
          <p>
            Clickable links from input text: {text}
          </p>
        </Linkify>
        <button style={{ margin: 20, padding: 5 }} onClick={generatePdf}>
          Generate PDF From Link
        </button>
      </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 React, { useState } from "react";
import Linkify from 'react-linkify';

// Home component for link conversion and PDF generation
export default function Home() {
  const [text, setText] = useState("");

  // Function to generate PDF from entered URL
  const generatePdf = async () => {
    try {
      const response = await fetch("/api/pdf?url=" + text);
      const blob = await response.blob();
      const url = window.URL.createObjectURL(new Blob([blob]));
      const link = document.createElement("a");
      link.href = url;
      link.setAttribute("download", "awesomeIron.pdf");
      document.body.appendChild(link);
      link.click();
      link.parentNode.removeChild(link);
    } catch (error) {
      console.error("Error generating PDF:", error);
    }
  };

  // Handle changes in the input text field
  const handleChange = (event) => {
    setText(event.target.value);
  };

  return (
    <div className={styles.container}>
      <Head>
        <title>Generate PDF Using IronPDF</title>
        <link rel="icon" href="/favicon.ico" />
      </Head>
      <main>
        <h1>Demo Linkify and Generate PDF Using IronPDF</h1>
        <p>
          <span>Enter URL to Linkify and Convert to PDF:</span>{" "}
        </p>
        <input type="text" value={text} onChange={handleChange} />
        <Linkify properties={{ target: '_blank' }}>
          <p>
            Clickable links from input text: {text}
          </p>
        </Linkify>
        <button style={{ margin: 20, padding: 5 }} onClick={generatePdf}>
          Generate PDF From Link
        </button>
      </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

코드 설명

  1. Linkify 연동:

    • Linkify 구성 요소는 링크 텍스트를 포함하는 HTML 태그를 둘러쌉니다.
    • 텍스트에서 감지된 URL이나 이메일 주소를 자동으로 클릭 가능한 링크로 변환합니다.
  2. PDF 생성:
    • 'PDF 생성' 버튼을 클릭하면 애플리케이션이 백엔드 API를 호출하여 URL에서 PDF를 생성합니다.
    • 이 API는 URL에서 웹 페이지를 가져와 다운로드 가능한 PDF 문서로 변환합니다.

PDF 생성 페이지 출력

linkify-react (작동 방식: 개발자를 위한 안내서): 그림 2 - PDF 생성에 대한 출력 페이지

결과 PDF

linkify-react (작동 방식: 개발자를 위한 안내서): 그림 3 - 'Generate PDF' 버튼 클릭으로 생성된 출력 PDF

IronPDF 라이선스

라이선스 키를 여기에 입력하세요:

import { IronPdfGlobalConfig, PdfDocument } from "@ironsoftware/ironpdf";

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

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

결론

React Linkify는 React 애플리케이션의 텍스트 콘텐츠 내에 클릭 가능한 링크를 만드는 과정을 간소화합니다. Linkify는 URL, 이메일 주소 및 기타 링크를 자동으로 감지하고 클릭 가능한 하이퍼링크로 변환하여 개발 워크플로를 간소화하고 사용자 경험을 향상시킵니다. React Linkify는 간편한 통합, 다양한 사용자 지정 옵션, 그리고 강력한 기능을 갖추고 있어 매력적이고 사용자 친화적인 인터페이스를 만들고자 하는 React 개발자에게 유용한 도구입니다.

게다가 IronPDF 포괄적인 PDF 생성, 조작 및 편집 기능을 애플리케이션에 통합하려는 개발자를 위해 맞춤 제작된 강력한 Node.js 라이브러리임이 입증되었습니다. IronPDF 다양한 형식을 PDF로 변환하고, 기존 PDF 문서를 편집하고, PDF 보안을 관리하는 기능을 지원하여 Node.js 환경에서 PDF 파일을 프로그래밍 방식으로 생성하고 사용자 정의할 수 있는 다재다능한 툴킷을 제공합니다. 이 라이브러리는 간단한 문서 생성부터 복잡한 문서 관리 작업에 이르기까지 광범위한 요구 사항을 충족하는 기능을 제공하므로 PDF를 다루는 Node.js 개발자에게 유용한 도구입니다.

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

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

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

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

아이언 서포트 팀

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