Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Re-render Reactjs components for print

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.

like image 653
Bill Avatar asked Jan 28 '16 21:01

Bill


People also ask

How do I print a component in React JS?

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.

How do I know if my components are Rerendered?

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.


1 Answers

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.

like image 193
Marc Greenstock Avatar answered Oct 01 '22 11:10

Marc Greenstock