I'm trying to prevent to have to hide/show a bunch of elements with CSS and instead render them only when printing, to do so I'm using this pattern:
const beforePrint = () => { console.log('beforePrint') };
const afterPrint = () => { console.log('afterPrint') };
if (window.matchMedia) {
const mediaQueryList = window.matchMedia('print');
mediaQueryList.addListener((mql) => {
if (mql.matches) {
beforePrint();
} else {
afterPrint();
}
});
}
window.addEventListener('beforeprint', this.handleBeforePrint);
window.addEventListener('afterprint', this.handleAfterPrint);
The console.log
are triggered as expected but when I'm rendering elements instead of doing a console.log
, it works only when the user does Ctrl+p and not when window.print
is triggered.
Here is my example https://pw74zpl44x.codesandbox.io/ and the code (in React but it doesn't matter) https://codesandbox.io/s/pw74zpl44x