print-hook
v0.1.0
Published
A tiny React hook for detecting the browser print lifecycle.
Maintainers
Readme
print-hook
A tiny React hook that tracks whether the browser is currently printing by listening to the native beforeprint and afterprint events.
- 🪶 Tiny and dependency-free
- ⚛️ Built for React
- 📦 Written in TypeScript
- 🌳 Tree-shakeable
- 🖨️ Simple API
Installation
npm install print-hookor
yarn add print-hookor
pnpm add print-hookUsage
import { usePrint } from "print-hook";
function App() {
const { isPrinting } = usePrint();
return <div>{isPrinting ? "Printing..." : "Not printing"}</div>;
}Callbacks
You can provide callbacks that are invoked when the browser enters or exits the print lifecycle.
import { usePrint } from "print-hook";
function App() {
const { isPrinting } = usePrint({
onBeforePrint(event) {
console.log("Before print", event);
},
onAfterPrint(event) {
console.log("After print", event);
},
});
return <p>{isPrinting ? "Printing..." : "Ready"}</p>;
}API
usePrint(options?)
Returns an object describing the current print state.
const { isPrinting } = usePrint(options);Options
| Name | Type | Description |
| --------------- | ------------------------ | ------------------------------------------------------ |
| onBeforePrint | (event: Event) => void | Called when the browser fires the beforeprint event. |
| onAfterPrint | (event: Event) => void | Called when the browser fires the afterprint event. |
Return Value
| Name | Type | Description |
| ------------ | --------- | -------------------------------------------------------- |
| isPrinting | boolean | Whether the browser is currently in the print lifecycle. |
Browser Support
This hook relies on the browser's native beforeprint and afterprint events. Support and behavior are determined by the browser implementation.
Requirements
- React 18+
- Modern browsers supporting the print events
License
MIT
