Last active
January 29, 2024 19:17
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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