Print React components in the browser
npx @tessl/cli install tessl/npm-react-to-print@3.1.00
# React To Print
1
2
React 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.
3
4
## Package Information
5
6
- **Package Name**: react-to-print
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install react-to-print`
10
11
## Core Imports
12
13
```typescript
14
import { useReactToPrint } from "react-to-print";
15
import type { UseReactToPrintFn, UseReactToPrintOptions } from "react-to-print";
16
import type { RefObject } from "react";
17
```
18
19
For CommonJS:
20
21
```javascript
22
const { useReactToPrint } = require("react-to-print");
23
```
24
25
## Basic Usage
26
27
```typescript
28
import { useReactToPrint } from "react-to-print";
29
import { useRef } from "react";
30
31
const contentRef = useRef<HTMLDivElement>(null);
32
const reactToPrintFn = useReactToPrint({ contentRef });
33
34
return (
35
<div>
36
<button onClick={reactToPrintFn}>Print</button>
37
<div ref={contentRef}>Content to print</div>
38
</div>
39
);
40
```
41
42
## Capabilities
43
44
### useReactToPrint Hook
45
46
The main hook that returns a function to trigger printing of React components.
47
48
```typescript { .api }
49
/**
50
* React hook that provides printing functionality for React components
51
* @param options - Configuration options for printing behavior
52
* @returns Function that can be called to trigger printing
53
*/
54
function useReactToPrint(options: UseReactToPrintOptions): UseReactToPrintFn;
55
```
56
57
**Usage Examples:**
58
59
```typescript
60
import { useReactToPrint } from "react-to-print";
61
import { useRef } from "react";
62
63
// Basic usage with contentRef
64
const contentRef = useRef<HTMLDivElement>(null);
65
const handlePrint = useReactToPrint({ contentRef });
66
67
// Advanced usage with callbacks and custom settings
68
const handlePrintWithOptions = useReactToPrint({
69
contentRef,
70
documentTitle: "My Report",
71
onBeforePrint: async () => {
72
console.log("Preparing to print...");
73
// Perform async operations before printing
74
},
75
onAfterPrint: () => {
76
console.log("Print dialog closed");
77
},
78
pageStyle: `
79
@media print {
80
body { margin: 0; }
81
.no-print { display: none !important; }
82
}
83
`,
84
fonts: [
85
{
86
family: "Roboto",
87
source: "https://fonts.googleapis.com/css?family=Roboto:300,400,500"
88
}
89
]
90
});
91
92
// Usage with dynamic content
93
const handlePrintDynamic = useReactToPrint({});
94
const printWithContent = () => {
95
const element = document.getElementById("dynamic-content");
96
handlePrintDynamic(() => element);
97
};
98
```
99
100
### Print Function Type
101
102
The function type returned by useReactToPrint.
103
104
```typescript { .api }
105
/**
106
* Function type for triggering print operations
107
* @param content - Optional content to print, can be a React event or function returning DOM element
108
*/
109
type UseReactToPrintFn = (content?: UseReactToPrintHookContent) => void;
110
```
111
112
### Content Parameter Type
113
114
The optional content parameter for the print function.
115
116
```typescript { .api }
117
/**
118
* Content that can be passed to the print function
119
* Allows for React event handlers or functions returning DOM elements
120
*/
121
type UseReactToPrintHookContent = React.UIEvent | (() => ContentNode);
122
```
123
124
## Configuration Options
125
126
### UseReactToPrintOptions Interface
127
128
Complete configuration interface for the useReactToPrint hook.
129
130
```typescript { .api }
131
/**
132
* Configuration options for useReactToPrint hook
133
*/
134
interface UseReactToPrintOptions {
135
/** One or more class names to pass to the print window, separated by spaces */
136
bodyClass?: string;
137
138
/**
139
* The ref pointing to the content to be printed.
140
* Alternatively, pass the ref directly to the callback returned by useReactToPrint
141
*/
142
contentRef?: RefObject<ContentNode>;
143
144
/** Set the title for printing when saving as a file. Ignored when passing a custom print option */
145
documentTitle?: string;
146
147
/** A list of fonts to load into the printing iframe. Useful for custom fonts */
148
fonts?: Font[];
149
150
/** Ignore all style and link stylesheet tags from head */
151
ignoreGlobalStyles?: boolean;
152
153
/**
154
* Set the nonce attribute for allow-listing script and style elements
155
* for Content Security Policy (CSP)
156
*/
157
nonce?: string;
158
159
/**
160
* Callback function that triggers after the print dialog is closed
161
* regardless of if the user selected to print or cancel
162
*/
163
onAfterPrint?: () => void;
164
165
/**
166
* Callback function that triggers before print. Can be used to change
167
* content before printing. Runs prior to print iframe being mounted.
168
*/
169
onBeforePrint?: () => Promise<void>;
170
171
/**
172
* Called if there is a printing error serious enough that printing cannot continue.
173
* Currently limited to Promise rejections in onBeforePrint and print functions.
174
*/
175
onPrintError?: (errorLocation: "onBeforePrint" | "print", error: Error) => void;
176
177
/**
178
* Override default styles for page printing. react-to-print sets basic styles
179
* to improve printing, notably removing browser headers and footers.
180
*/
181
pageStyle?: string;
182
183
/**
184
* Preserve the print iframe after printing. Useful for debugging
185
* by inspecting the print iframe.
186
*/
187
preserveAfterPrint?: boolean;
188
189
/**
190
* Custom print function to use instead of window.print.
191
* Use for non-browser environments such as Electron.
192
*/
193
print?: (target: HTMLIFrameElement) => Promise<any>;
194
195
/** When passed, prevents console logging of errors */
196
suppressErrors?: boolean;
197
198
/** When passed, shadow root content will be copied */
199
copyShadowRoots?: boolean;
200
}
201
```
202
203
## Type Definitions
204
205
### ContentNode Type
206
207
Valid DOM content nodes that can be printed.
208
209
```typescript { .api }
210
/**
211
* Valid DOM content nodes for printing operations
212
*/
213
type ContentNode = Element | Text | null | undefined;
214
```
215
216
### Font Interface
217
218
Font configuration for loading custom fonts in the print window.
219
220
```typescript { .api }
221
/**
222
* Font configuration for custom fonts in print window
223
* Based on the Web API FontFace constructor
224
*/
225
interface Font {
226
/** Font family name */
227
family: string;
228
/** Font source URL or data URI */
229
source: string;
230
/** Optional font weight (e.g., "400", "bold") */
231
weight?: string;
232
/** Optional font style (e.g., "normal", "italic") */
233
style?: string;
234
}
235
```
236
237
**Font Usage Example:**
238
239
```typescript
240
const fonts: Font[] = [
241
{
242
family: "Open Sans",
243
source: "https://fonts.googleapis.com/css2?family=Open+Sans:wght@400;600&display=swap"
244
},
245
{
246
family: "Roboto Mono",
247
source: "https://fonts.googleapis.com/css2?family=Roboto+Mono:wght@400&display=swap",
248
weight: "400",
249
style: "normal"
250
}
251
];
252
253
const handlePrint = useReactToPrint({
254
contentRef,
255
fonts
256
});
257
```
258
259
## Error Handling
260
261
The library provides error handling through the `onPrintError` callback:
262
263
```typescript
264
const handlePrint = useReactToPrint({
265
contentRef,
266
onPrintError: (errorLocation, error) => {
267
console.error(`Print error in ${errorLocation}:`, error);
268
// Handle error appropriately - maybe show user notification
269
// or attempt to retry printing
270
}
271
});
272
```
273
274
## Browser Compatibility
275
276
- Compatible with most modern browsers
277
- **Known limitations:**
278
- Mobile browsers in WebView may not work properly
279
- Firefox Android does not support window.print
280
- Some mobile browsers may open native Share action instead of printing
281
- onAfterPrint may fire immediately on newer Safari versions
282
283
## Common Use Cases
284
285
**Invoice Printing:**
286
```typescript
287
const InvoiceComponent = () => {
288
const invoiceRef = useRef<HTMLDivElement>(null);
289
const handlePrintInvoice = useReactToPrint({
290
contentRef: invoiceRef,
291
documentTitle: `Invoice-${invoiceNumber}`,
292
pageStyle: `
293
@media print {
294
body { font-family: Arial, sans-serif; }
295
.invoice-header { border-bottom: 2px solid #000; }
296
}
297
`
298
});
299
300
return (
301
<div>
302
<button onClick={handlePrintInvoice}>Print Invoice</button>
303
<div ref={invoiceRef}>
304
{/* Invoice content */}
305
</div>
306
</div>
307
);
308
};
309
```
310
311
**Report with Custom Fonts:**
312
```typescript
313
const ReportComponent = () => {
314
const reportRef = useRef<HTMLDivElement>(null);
315
const handlePrintReport = useReactToPrint({
316
contentRef: reportRef,
317
documentTitle: "Monthly Report",
318
fonts: [
319
{
320
family: "Helvetica",
321
source: "https://fonts.googleapis.com/css2?family=Inter:wght@400;600&display=swap"
322
}
323
],
324
onBeforePrint: async () => {
325
// Load additional data or prepare charts
326
await prepareReportData();
327
}
328
});
329
330
return (
331
<div>
332
<button onClick={handlePrintReport}>Print Report</button>
333
<div ref={reportRef}>
334
{/* Report content */}
335
</div>
336
</div>
337
);
338
};
339
```