I have a gallery component that uses the current window size to determine how large to make the gallery items. I've also hooked the window resize events so that the gallery items are resized correctly as the window is resized.
In Chrome, if a user then prints the gallery, the items are not being resized to fit the printed page. Instead they are just using the last size calculated for the window size. This is true even when switching from portrait to landscape in the print options.
Is there any way to force react to re-render components when the print dialog is being opened and when the page layout is switched from portrait to landscape? I thought the print dialog would re-render the page with the new dimensions but that doesn't seem to be the case.
To print a React component on click of a button, we can use the react-to-print library. to use it. We wrap the component that triggers the opening of the print dialog in the PrintContextConsumer . And we wrap the PrintContextConsumer with the ReactToPrint component.
There's a checkbox well hidden in the React DevTools settings that allows you to visually highlight the components that rerendered. To enable it, go to "Profiler" >> click the "Cog wheel" on the right side of the top bar >> "General" tab >> Check the "Highlight updates when components render." checkbox.
When you print a page, the browser takes a snapshot of the current DOM and applies the print
media styles. Your problem is the elements on your DOM are dependent on the dimensions of the screen.
Window resize events will help to rearrange your components when the user resizes their screen but they are not triggered when the user prints. There are however ways in which you can listen to an event when the user prints the page.
window.onbeforeprint will trigger when the user prints the page. On event you either resize the screen to make the window resize events trigger or re-render your components some other way. It is not supported in chrome although take a look at this stackoverflow post, it explains how you can use window.matchMedia('print')
instead.
It's always best to depend on css media queries rather than on the screen dimensions and resize events, but sometimes that is not always possible.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With