Print React Components

3.3.0 · active · verified Sun Apr 19

react-to-print is a widely used React component library designed to facilitate printing the contents of React components directly from the browser. It works by creating a temporary iframe, injecting the specified component's DOM, and then triggering the browser's print dialog. The current stable version is 3.3.0, released in February 2026, with frequent patch and minor releases, indicating active maintenance and development. Key differentiators include its `useReactToPrint` hook for functional components, extensive customization options for print styles (like `pageStyle`, `bodyClass`, `ignoreGlobalStyles`), and callbacks for managing print lifecycle events (`onBeforePrint`, `onAfterPrint`, `onPrintError`). It also provides support for loading custom fonts and handling shadow DOMs, addressing common challenges in web printing.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates basic usage of `useReactToPrint` hook to print a component's content, including ref setup, print options, and lifecycle callbacks.

import { useReactToPrint } from 'react-to-print';
import React, { useRef } from 'react';

const MyPrintableComponent = () => {
  const componentRef = useRef<HTMLDivElement>(null);

  const handlePrint = useReactToPrint({
    content: () => componentRef.current,
    documentTitle: 'My Custom Print Document',
    pageStyle: '@page { size: auto; margin: 25mm; } @media print { body { -webkit-print-color-adjust: exact; } }',
    onBeforePrint: async () => {
      console.log('onBeforePrint callback!');
      // Potentially fetch data or modify component state before print
      await new Promise(resolve => setTimeout(resolve, 500)); // Simulate async work
    },
    onAfterPrint: () => console.log('onAfterPrint callback!')
  });

  return (
    <div>
      <button onClick={handlePrint}>Print this out!</button>
      <div ref={componentRef} style={{ padding: '20px', border: '1px solid #ccc' }}>
        <h1>Document Title</h1>
        <p>This is the content that will be printed. It can be any React component's output.</p>
        <p>Example: User ID: {process.env.REACT_APP_USER_ID ?? 'N/A'}</p>
        <ul>
          <li>Item 1</li>
          <li>Item 2</li>
          <li>Item 3</li>
        </ul>
      </div>
    </div>
  );
};

export default MyPrintableComponent;

view raw JSON →