Print React components in the browser
npx @tessl/cli install tessl/npm-react-to-print@3.1.0React To Print provides a simple React hook for printing React components directly in the browser. It creates a seamless print interface by rendering components in a separate print window with extensive customization options including custom styling, fonts, document titles, and callback functions for before/after print events.
npm install react-to-printimport { useReactToPrint } from "react-to-print";
import type { UseReactToPrintFn, UseReactToPrintOptions } from "react-to-print";
import type { RefObject } from "react";For CommonJS:
const { useReactToPrint } = require("react-to-print");import { useReactToPrint } from "react-to-print";
import { useRef } from "react";
const contentRef = useRef<HTMLDivElement>(null);
const reactToPrintFn = useReactToPrint({ contentRef });
return (
<div>
<button onClick={reactToPrintFn}>Print</button>
<div ref={contentRef}>Content to print</div>
</div>
);The main hook that returns a function to trigger printing of React components.
/**
* React hook that provides printing functionality for React components
* @param options - Configuration options for printing behavior
* @returns Function that can be called to trigger printing
*/
function useReactToPrint(options: UseReactToPrintOptions): UseReactToPrintFn;Usage Examples:
import { useReactToPrint } from "react-to-print";
import { useRef } from "react";
// Basic usage with contentRef
const contentRef = useRef<HTMLDivElement>(null);
const handlePrint = useReactToPrint({ contentRef });
// Advanced usage with callbacks and custom settings
const handlePrintWithOptions = useReactToPrint({
contentRef,
documentTitle: "My Report",
onBeforePrint: async () => {
console.log("Preparing to print...");
// Perform async operations before printing
},
onAfterPrint: () => {
console.log("Print dialog closed");
},
pageStyle: `
@media print {
body { margin: 0; }
.no-print { display: none !important; }
}
`,
fonts: [
{
family: "Roboto",
source: "https://fonts.googleapis.com/css?family=Roboto:300,400,500"
}
]
});
// Usage with dynamic content
const handlePrintDynamic = useReactToPrint({});
const printWithContent = () => {
const element = document.getElementById("dynamic-content");
handlePrintDynamic(() => element);
};The function type returned by useReactToPrint.
/**
* Function type for triggering print operations
* @param content - Optional content to print, can be a React event or function returning DOM element
*/
type UseReactToPrintFn = (content?: UseReactToPrintHookContent) => void;The optional content parameter for the print function.
/**
* Content that can be passed to the print function
* Allows for React event handlers or functions returning DOM elements
*/
type UseReactToPrintHookContent = React.UIEvent | (() => ContentNode);Complete configuration interface for the useReactToPrint hook.
/**
* Configuration options for useReactToPrint hook
*/
interface UseReactToPrintOptions {
/** One or more class names to pass to the print window, separated by spaces */
bodyClass?: string;
/**
* The ref pointing to the content to be printed.
* Alternatively, pass the ref directly to the callback returned by useReactToPrint
*/
contentRef?: RefObject<ContentNode>;
/** Set the title for printing when saving as a file. Ignored when passing a custom print option */
documentTitle?: string;
/** A list of fonts to load into the printing iframe. Useful for custom fonts */
fonts?: Font[];
/** Ignore all style and link stylesheet tags from head */
ignoreGlobalStyles?: boolean;
/**
* Set the nonce attribute for allow-listing script and style elements
* for Content Security Policy (CSP)
*/
nonce?: string;
/**
* Callback function that triggers after the print dialog is closed
* regardless of if the user selected to print or cancel
*/
onAfterPrint?: () => void;
/**
* Callback function that triggers before print. Can be used to change
* content before printing. Runs prior to print iframe being mounted.
*/
onBeforePrint?: () => Promise<void>;
/**
* Called if there is a printing error serious enough that printing cannot continue.
* Currently limited to Promise rejections in onBeforePrint and print functions.
*/
onPrintError?: (errorLocation: "onBeforePrint" | "print", error: Error) => void;
/**
* Override default styles for page printing. react-to-print sets basic styles
* to improve printing, notably removing browser headers and footers.
*/
pageStyle?: string;
/**
* Preserve the print iframe after printing. Useful for debugging
* by inspecting the print iframe.
*/
preserveAfterPrint?: boolean;
/**
* Custom print function to use instead of window.print.
* Use for non-browser environments such as Electron.
*/
print?: (target: HTMLIFrameElement) => Promise<any>;
/** When passed, prevents console logging of errors */
suppressErrors?: boolean;
/** When passed, shadow root content will be copied */
copyShadowRoots?: boolean;
}Valid DOM content nodes that can be printed.
/**
* Valid DOM content nodes for printing operations
*/
type ContentNode = Element | Text | null | undefined;Font configuration for loading custom fonts in the print window.
/**
* Font configuration for custom fonts in print window
* Based on the Web API FontFace constructor
*/
interface Font {
/** Font family name */
family: string;
/** Font source URL or data URI */
source: string;
/** Optional font weight (e.g., "400", "bold") */
weight?: string;
/** Optional font style (e.g., "normal", "italic") */
style?: string;
}Font Usage Example:
const fonts: Font[] = [
{
family: "Open Sans",
source: "https://fonts.googleapis.com/css2?family=Open+Sans:wght@400;600&display=swap"
},
{
family: "Roboto Mono",
source: "https://fonts.googleapis.com/css2?family=Roboto+Mono:wght@400&display=swap",
weight: "400",
style: "normal"
}
];
const handlePrint = useReactToPrint({
contentRef,
fonts
});The library provides error handling through the onPrintError callback:
const handlePrint = useReactToPrint({
contentRef,
onPrintError: (errorLocation, error) => {
console.error(`Print error in ${errorLocation}:`, error);
// Handle error appropriately - maybe show user notification
// or attempt to retry printing
}
});Invoice Printing:
const InvoiceComponent = () => {
const invoiceRef = useRef<HTMLDivElement>(null);
const handlePrintInvoice = useReactToPrint({
contentRef: invoiceRef,
documentTitle: `Invoice-${invoiceNumber}`,
pageStyle: `
@media print {
body { font-family: Arial, sans-serif; }
.invoice-header { border-bottom: 2px solid #000; }
}
`
});
return (
<div>
<button onClick={handlePrintInvoice}>Print Invoice</button>
<div ref={invoiceRef}>
{/* Invoice content */}
</div>
</div>
);
};Report with Custom Fonts:
const ReportComponent = () => {
const reportRef = useRef<HTMLDivElement>(null);
const handlePrintReport = useReactToPrint({
contentRef: reportRef,
documentTitle: "Monthly Report",
fonts: [
{
family: "Helvetica",
source: "https://fonts.googleapis.com/css2?family=Inter:wght@400;600&display=swap"
}
],
onBeforePrint: async () => {
// Load additional data or prepare charts
await prepareReportData();
}
});
return (
<div>
<button onClick={handlePrintReport}>Print Report</button>
<div ref={reportRef}>
{/* Report content */}
</div>
</div>
);
};