A Simple Way to Print Certain Elements and Hide Others Using CSS and React
I was recently working on a React web app my wife asked me to make that allows her to select 5–7 meals from a long list of meals we both enjoy. After choosing sides for each selected meal, the end goal is to have a consolidated list of ingredients with checkboxes to mark ingredients you already have, and ones you’ll need to get from the store. When I got to the part where the ingredients were on the screen, she mentioned she would want to have it printed out. Except, we only wanted the ingredients to be printed out, and not all the unnecessary elements of the nav bar and header at the top. I had no idea how to do it, so I figured I would share with you all the simple solution that worked for me!
To demonstrate, I’ve built out a super simple React app named PrintaBull. After throwing some text and images on the screen, I’ll target certain elements on the page I want to hide, allowing the remaining visible elements to be printable. If the print preview looks weird, I’ll address any styling issues for the printable page without affecting the web page look.
Here’s what I’m working with:
Notice line 13, the <button> has an arrow function in the “onClick” which prompts the print preview to open.
The app looks like this:
CSS I’ve used to this point:
Print preview after hitting the button currently looks like:
So we got the page to pull up in the browser’s print preview, and it even politely changed our header’s blue background to white— let’s say we want to get rid of the images (not the logo) in the printout, without affecting the website images, in an effort to save ink. We would add this CSS:
This allows us to not only hide elements from being printed, but change any CSS attributes for any element on the page. As you can see in the next image, we got rid of the images in our printable page, but the formatting is still off:
Let’s try to get all the text on one page:
If you compare this CSS to the original CSS on lines 1–48 above, all I have done is overwrite the original styling for each desired element to format the page for printing.
This is our new result:
As mentioned earlier, this does not affect the CSS anywhere except the print preview/printable page. And that’s pretty much it folks! This is the super simple solution I used to print some elements, adjust the styling on others, and hide the rest. If you made it this far, thanks for reading, I hope it was beneficial for you :) happy coding.