NODE HELP

linkify-react (How It Works: A Guide for Developers)

Published February 19, 2025
Share:

Introduction

In the wide world of web development, creating clickable links or an anchor tag within text is a fundamental task. Whether you're building a blog, a social media platform, or an email client, the ability to automatically detect and convert URLs, email addresses, and other text into clickable links is crucial for providing a seamless user experience. Enter Linkify React – a powerful npm package designed to streamline this process in React applications. In this article, we'll explore how you can use Linkify to simplify link creation in your React projects, accompanied by code examples to demonstrate its usage.

On top of this, we'll also introduce you to IronPDF, a versatile library that allows you to generate high-quality PDF documents from your web pages. We'll show you that by using IronPDF alongside Linkify, you can easily create PDFs that preserve the clickable links identified and converted by Linkify, ensuring that your documents maintain the same interactivity as your web content.

Getting Started with the Linkify React Component

Linkify React is a lightweight and easy-to-use npm package that automates the conversion of plain text containing URLs, email addresses, and other discovered links within child strings into clickable hyperlinks as nested elements. It eliminates the need for manual link parsing and formatting, saving developers valuable time and effort. Let's dive into how you can integrate Linkify into your React applications.

Installation

To get started with React Linkify, you first need to install it as a dependency in your project. You can do this using npm or yarn. Open your terminal and run the following command:

npm install react-linkify
//or
yarn add react-linkify

Usage

Once React Linkify is installed, you can easily integrate it into your React components. Here's a simple example demonstrating how to use React Linkify to render clickable links within text content:

import React from 'react';
import Linkify from 'react-linkify';
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

In this example, we import the Linkify component from the react-linkify package and wrap our text content inside it. React Linkify automatically detects URLs and email addresses within the text and converts them into clickable hyperlinks.

Customization

Linkify provides various props, attributes, and options to customize the behavior and appearance of the generated links. For example, you can specify target attributes to control how the links are opened (e.g., as external links leading to a new tab, or as anchor tags). Here's how you can customize the behavior of React Linkify:

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

Introducing IronPDF

IronPDF is a powerful npm package designed to facilitate PDF generation within Node.js applications. It allows you to create PDF documents from HTML content, URLs, or existing PDF files. Whether you're generating invoices, reports, or any other type of document, IronPDF simplifies the process with its intuitive API and robust feature set.

linkify-react (How It Works: A Guide for Developers): Figure 1 - IronPDF for Node.js: The Node.js PDF Library Website

Key features of IronPDF include

1. HTML to PDF Conversion

Convert HTML element interface content into PDF documents effortlessly. This feature is particularly useful for generating dynamic PDFs from web content.

2. URL to PDF Conversion

Generate PDFs directly from URLs. This allows you to capture the content of web pages and save them as PDF files programmatically.

3. PDF Manipulation

Merge, split, and manipulate existing PDF documents with ease. IronPDF provides functionalities to manipulate PDF files, such as appending pages, splitting documents, and more.

4. PDF Security

Secure your PDF documents by encrypting them with passwords or applying digital signatures. IronPDF offers options to protect your sensitive documents from unauthorized access.

5. High-Quality Output

Produce high-quality PDF documents with precise rendering of text, images, and formatting. IronPDF ensures that your generated PDFs maintain fidelity to the original content.

6. Cross-Platform Compatibility

IronPDF is compatible with various platforms, including Windows, Linux, and macOS, making it suitable for a wide range of development environments.

7. Simple Integration

Easily integrate IronPDF into your Node.js applications using its npm package. The API is well-documented, making it straightforward to incorporate PDF generation capabilities into your projects.

Whether you're building a web application, a server-side script, or a command-line tool, IronPDF empowers you to create professional-grade PDF documents efficiently and reliably.

Generate PDF Documents using IronPDF and Linkify React

Install Dependencies: First, create a new Next.js project (if you haven’t already) using the following command:

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

Next, navigate to your project directory:

cd linkify-ironpdf

Install the required packages:

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

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:

PDF Generation API: The first step is to create a backend API to generate the PDF document. Since IronPDF only runs server side we need to create an API to call when a user wants to generate PDF. Create a file in path pages/api/pdf.js and add the below contents.

IronPDF also requires a license key, you can get it from the license page and place it in the below code:

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

Created using IronPDF and Linkify, the index.js code below sets up the PDF generation page for the user:

import Head from "next/head";
import styles from "../styles/Home.module.css";
import React, { useState } from "react";
import Linkify from 'react-linkify';
export default function Home() {
  const [text, setText] = useState("");
  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);
    }
  };
  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>
        <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

Code Explanation

  1. Surround the HTML tag which contains the link text with the Linkify component
  2. When the user inputs any text, if this is a link then the component automatically converts it to a link and displays the clickable link.
  3. When the 'Generate PDF' button is clicked, the link is sent to the backend PDF-generating API, and a PDF document is generated from the URL link.

Outputted PDF Generating Page

linkify-react (How It Works: A Guide for Developers): Figure 2 - Outputed page for PDF generation

Resulting PDF

linkify-react (How It Works: A Guide for Developers): Figure 3 - Outputted PDF from clicking the 'Generate PDF' button

IronPDF License

TheIronPDF.

Place the License Key here:

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

Conclusion

React Linkify simplifies the process of creating clickable links within text content in React applications. By automating the detection and conversion of URLs, email addresses, and other links into clickable hyperlinks, Linkify streamlines the development workflow and enhances the user experience. With its easy integration, customization options, and robust functionality, React Linkify is a valuable tool for React developers seeking to create engaging and user-friendly interfaces.

On top of that,IronPDF has proved to be a robust node.js library tailored for developers looking to integrate comprehensive PDF generation, manipulation, and editing capabilities into their applications. With support for converting various formats to PDF, editing existing PDF documents, and managing PDF security, IronPDF provides a versatile toolkit for creating and customizing PDF files programmatically within the node.js environment. Its features cater to a wide range of needs, from simple document generation to complex document management tasks, making it a valuable tool for node.js developers working with PDFs.

Jordi Bardia

Jordi Bardia

Software Engineer

 LinkedIn |  Website

Jordi is most proficient in Python, C# and C++, when he isn’t leveraging his skills at Iron Software; he’s game programming. Sharing responsibilities for product testing, product development and research, Jordi adds immense value to continual product improvement. The varied experience keeps him challenged and engaged, and he says it’s one of his favorite aspects of working with Iron Software. Jordi grew up in Miami, Florida and studied Computer Science and Statistics at University of Florida.
NEXT >
next-auth NPM (How It Works For Developers)