React detect 🖨

Drew Goodwin
Mar 23, 2017 · 2 min read

The standard advice to detect and handle print formatting for your web app is to use media queries. This works (and should be used) for most cases, but what if you really do need JavaScript? React applications, for example, are more likely to create styles dynamically with JavaScript for charts and other width-sensitive components. Or perhaps you want to log print events. I didn’t find any solution for this, so I published react-detect-print.

It’s a higher order component that sends a printing prop with a value of true or false to the wrapped component, indicating the state of printing. The approach to detect printing is adapted from this blog post. It hasn’t been widely tested and probably has issues, so use at your own risk.

Example

Check out react-detect-print-example. The printed page size is set to letter (see /src/index.css), which seems to require a width of 816 pixels to fit perfectly on a page (96dpi x 8.5in). Landscape orientation is not (yet?) handled by the library. Running the example should show a page like the following:

Example in the browser (not yet printing).

However, when printing, you should see the value of the printing flag change to true. The change in prop value can be used to cause children to re-render, updating themselves for the printed page:

Example in print preview, showing adjusted widths.

Drew Goodwin

Written by

The audience is us.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade