Skip to content

Instantly share code, notes, and snippets.

@FredrikAugust
Last active January 29, 2024 19:17
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save FredrikAugust/e2c5f7c5865be41fa52ab4fd9a5d2853 to your computer and use it in GitHub Desktop.
Save FredrikAugust/e2c5f7c5865be41fa52ab4fd9a5d2853 to your computer and use it in GitHub Desktop.
Custom React hook for listening to whether or not the window is currently printing.
/**
* Allows you to subscribe to whether or not the window is currently printing (user invoked the system print dialog).
*
* @returns Whether or not the document is currently printing.
*/
export default function useIsPrinting(): boolean {
const [printing, setIsPrinting] = useState(
window.matchMedia('print').matches
);
useEffect(() => {
const beforeprint = () => setIsPrinting(true);
const afterprint = () => setIsPrinting(false);
window.addEventListener('beforeprint', beforeprint);
window.addEventListener('afterprint', afterprint);
return () => {
window.removeEventListener('beforeprint', beforeprint);
window.removeEventListener('afterprint', afterprint);
};
}, []);
return printing;
}
type UseIsPrintingOptions = {
beforePrintCallback: () => void;
afterPrintCallback: () => void;
};
/**
* Allows you to subscribe to whether or not the window is currently printing (user invoked the system print dialog).
*
* @param options An optional object with callbacks to be invoked when the window goes into and/or out of printing mode.
* @returns Whether or not the document is currently printing.
*/
export default function useIsPrinting(options?: UseIsPrintingOptions): boolean {
const [printing, setIsPrinting] = useState(
window.matchMedia('print').matches
);
useEffect(() => {
const beforeprint = () => {
options?.beforePrintCallback?.call(null);
setIsPrinting(true);
};
const afterprint = () => {
options?.afterPrintCallback?.call(null);
setIsPrinting(false);
};
window.addEventListener('beforeprint', beforeprint);
window.addEventListener('afterprint', afterprint);
return () => {
window.removeEventListener('beforeprint', beforeprint);
window.removeEventListener('afterprint', afterprint);
};
}, [options?.afterPrintCallback, options?.beforePrintCallback]);
return printing;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment