{"id":11887,"library":"react-to-print","title":"Print React Components","description":"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.","status":"active","version":"3.3.0","language":"javascript","source_language":"en","source_url":"https://github.com/MatthewHerbst/react-to-print","tags":["javascript","react","print","reactjs","react-to-print","typescript"],"install":[{"cmd":"npm install react-to-print","lang":"bash","label":"npm"},{"cmd":"yarn add react-to-print","lang":"bash","label":"yarn"},{"cmd":"pnpm add react-to-print","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Peer dependency for React applications. Required for rendering and managing component lifecycle.","package":"react","optional":false}],"imports":[{"note":"Primary hook for functional components. Package is ESM-first; CommonJS `require` is not the idiomatic way.","wrong":"const useReactToPrint = require('react-to-print');","symbol":"useReactToPrint","correct":"import { useReactToPrint } from 'react-to-print';"},{"note":"Class component wrapper (legacy API). While still supported, `useReactToPrint` is recommended for new development.","wrong":"import { ReactToPrint } from 'react-to-print';","symbol":"ReactToPrint","correct":"import ReactToPrint from 'react-to-print';"},{"note":"While `RefObject` is a React type, it's crucial for correct TypeScript usage with `contentRef` option, ensuring type safety when referencing DOM elements to be printed.","symbol":"RefObject","correct":"import React, { useRef, type RefObject } from 'react';\n// ...or for use in a function:\nconst contentRef = useRef<HTMLDivElement>(null);"}],"quickstart":{"code":"import { useReactToPrint } from 'react-to-print';\nimport React, { useRef } from 'react';\n\nconst MyPrintableComponent = () => {\n  const componentRef = useRef<HTMLDivElement>(null);\n\n  const handlePrint = useReactToPrint({\n    content: () => componentRef.current,\n    documentTitle: 'My Custom Print Document',\n    pageStyle: '@page { size: auto; margin: 25mm; } @media print { body { -webkit-print-color-adjust: exact; } }',\n    onBeforePrint: async () => {\n      console.log('onBeforePrint callback!');\n      // Potentially fetch data or modify component state before print\n      await new Promise(resolve => setTimeout(resolve, 500)); // Simulate async work\n    },\n    onAfterPrint: () => console.log('onAfterPrint callback!')\n  });\n\n  return (\n    <div>\n      <button onClick={handlePrint}>Print this out!</button>\n      <div ref={componentRef} style={{ padding: '20px', border: '1px solid #ccc' }}>\n        <h1>Document Title</h1>\n        <p>This is the content that will be printed. It can be any React component's output.</p>\n        <p>Example: User ID: {process.env.REACT_APP_USER_ID ?? 'N/A'}</p>\n        <ul>\n          <li>Item 1</li>\n          <li>Item 2</li>\n          <li>Item 3</li>\n        </ul>\n      </div>\n    </div>\n  );\n};\n\nexport default MyPrintableComponent;","lang":"typescript","description":"Demonstrates basic usage of `useReactToPrint` hook to print a component's content, including ref setup, print options, and lifecycle callbacks."},"warnings":[{"fix":"Migrate class-based `ReactToPrint` usage to the `useReactToPrint` hook for functional components. Ensure `content` option returns the DOM node to be printed.","message":"Version 3.x introduced a significant API change, shifting from a class component (`ReactToPrint`) to a functional hook (`useReactToPrint`) as the primary interface. While the class component is still available, the hook is the recommended and more modern approach.","severity":"breaking","affected_versions":">=3.0.0"},{"fix":"Use the `pageStyle` option for custom print CSS, or ensure `<link>` and `<style>` tags are properly handled by the browser's print engine. For external stylesheets, ensure they are accessible and loaded within the print iframe. Consider `onBeforePrint` to dynamically inject print-specific styles.","message":"External CSS files and global styles might not apply correctly to the printed content if they are not explicitly loaded or if the `ignoreGlobalStyles` option is used incorrectly. Browser print styles often differ from screen styles.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Always check for `componentRef.current` before returning it in the `content` callback, e.g., `content: () => componentRef.current || document.createElement('div')` or ensure the component is mounted before triggering print. The hook's internal logic handles a null return by showing an error.","message":"When using `content: () => componentRef.current`, ensure that `componentRef.current` is not `null` or `undefined` at the time `handlePrint` is called. This can happen if the component is unmounted or the ref isn't properly attached yet.","severity":"gotcha","affected_versions":">=3.0.0"},{"fix":"If specific actions need to occur only upon successful print, you might need to implement a more complex tracking mechanism, potentially by combining `onBeforePrint` and a timeout, or accepting the browser's native behavior.","message":"The `onAfterPrint` callback triggers regardless of whether the user chose to print or canceled the print dialog. This can lead to unexpected side effects if state changes are based solely on this callback.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Enable the `copyShadowRoots: true` option if your content includes shadow DOMs. Be aware of potential performance impacts on very large documents and test thoroughly.","message":"Printing content with shadow DOMs (e.g., from Web Components) can be slow or lead to missing styles if `copyShadowRoots` is not enabled or used improperly, especially for large documents.","severity":"gotcha","affected_versions":">=3.0.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Ensure the `ref` (e.g., `componentRef`) is correctly attached to the DOM element you intend to print and that the element is mounted when the print function is invoked. Check the `content` callback always returns a valid DOM element.","cause":"The `content` option in `useReactToPrint` returned `null` or `undefined`, meaning the `ref` to the component to be printed was not yet available or was incorrectly passed.","error":"TypeError: Cannot read properties of null (reading 'current') at content"},{"fix":"Use the `pageStyle` option to inject specific print styles. For dynamic styles, ensure they are rendered into static CSS that can be copied. Check if `ignoreGlobalStyles` is inadvertently set to `true`.","cause":"Browser print stylesheets (`@media print`) are not being applied, or dynamic styles (e.g., CSS-in-JS) are not being transferred to the print iframe.","error":"Styles are missing or incorrect in the printed output."},{"fix":"Inspect the `print` iframe (by setting `preserveAfterPrint: true`) to see what content it received. Ensure the component to be printed has visible dimensions and styles that allow it to be rendered in a print-friendly manner. Use `onBeforePrint` to delay printing until content is fully rendered.","cause":"The element referenced by `contentRef` might be hidden by CSS, or its dimensions are zero in the print context, or JavaScript rendering is incomplete before print.","error":"Prints a blank page or only part of the content."},{"fix":"If using the class component, ensure it's imported as a default import: `import ReactToPrint from 'react-to-print';`. For new code, prefer the `useReactToPrint` hook: `import { useReactToPrint } from 'react-to-print';`.","cause":"Attempting to use the `ReactToPrint` class component with an incorrect named import, or in an environment where it's not available.","error":"ReferenceError: ReactToPrint is not defined"}],"ecosystem":"npm"}