DEV Community

Cover image for Printing in React Made Easy With React-To-Print
NJOKU SAMSON EBERE
NJOKU SAMSON EBERE

Posted on

Printing in React Made Easy With React-To-Print

Introduction

It is easy to use the regular javaScript print() method to trigger the printing of a whole window or page of a website.

However, we do not always desire that. We may be interested in printing just a part of that website. In fact, we may not even desire that the part we want to print be visible to the user until the print button is clicked. In doing all these, you still want the styling of that portion to maintained.

All these problem has been fixed in React using the React-To-Print npm package. I will be demonstrating how you can print using the React-To-Print and even hide the component being printed while maintaining the CSS styles.

What is React-To-Print?

This is an npm package that aims to give end users the ability to print out the contents of a component by popping up a print window with CSS styles copied over as well.

Prerequisite

This tutorial assumes that you already have the basic knowledge of JavaScript and React especially the difference between class and functional component.

Starter project

We will be using the app we created here as the starter project of this tutorial. To get the project setup in your local machine, do the following:

  • Clone the repo ```javascript

git clone https://github.com/EBEREGIT/react-auth


* Install the dependencies
```javascript



npm install



Enter fullscreen mode Exit fullscreen mode
  • Load the project on your browser ```javascript

npm start


> You should have this view on your browser now
![Starter Project Initial View](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v558vyh16t2k1kk03bas.JPG)

*Awesome!*

## Building the component to be Printed
* Create a component to contain the button that triggers the printing of the desired component

```javascript



import React, { useRef } from "react";
import { Button } from "react-bootstrap";
import ReactToPrint from "react-to-print";

export default function PrintComponent() {
  let componentRef = useRef();

  return (
    <>
      <div>
        {/* button to trigger printing of target component */}
        <ReactToPrint
          trigger={() => <Button>Print this out!</Button>}
          content={() => componentRef}
        />

        {/* component to be printed */}
        <ComponentToPrint ref={(el) => (componentRef = el)} />
      </div>
    </>
  );
}



Enter fullscreen mode Exit fullscreen mode

From the code above, we imported the ReactToPrint library, then we called the ReactToPrint component in the body. The ReactToPrint holds the trigger (this can be a button or what so ever we choose) and the content (this is a reference to the component that is to be printed).

Below the ReactToPrint component is the component to be printed with a ref connecting it to the ReactToPrint content props.

Now, let's build the ComponentToPrint component with the following code:




class ComponentToPrint extends React.Component {
  render() {
    return (
      <div>
        <h2 style={{color: "green"}}>Attendance</h2>
        <table>
          <thead>
            <th>S/N</th>
            <th>Name</th>
            <th>Email</th>
          </thead>
          <tbody>
            <tr>
              <td>1</td>
              <td>Njoku Samson</td>
              <td>samson@yahoo.com</td>
            </tr>
            <tr>
              <td>2</td>
              <td>Ebere Plenty</td>
              <td>ebere@gmail.com</td>
            </tr>
            <tr>
              <td>3</td>
              <td>Undefined</td>
              <td>No Email</td>
            </tr>
          </tbody>
        </table>
      </div>
    );
  }
}



Enter fullscreen mode Exit fullscreen mode
  • Add the following styles in the index.css



thead th {
  padding-right: 50px;
}



Enter fullscreen mode Exit fullscreen mode
  • Render the component in the freeComponent.js file like so:



<PrintComponent />



Enter fullscreen mode Exit fullscreen mode

Don't forget to import the component on top of the file like so:




import PrintComponent from "./PrintComponent";



Enter fullscreen mode Exit fullscreen mode
  • Now, navigate to http://localhost:3000/free and you should have the following screen:

Screen with Print component

  • When you click on the blue button, you should have the print dialogue with the print preview print dialogue with the print preview Notice that the print preview has only the component that we desire to print and the CSS styles are not left out. How awesome!!!

Hiding the component to be printed

Sometimes, we don't want our users to see what is to be printed until the print button is clicked. This is useful when you are generating invoice, receipt and so on. To make this happen, go to the PrintComponent component in the PrintComponent.js file.

Replace <ComponentToPrint ref={(el) => (componentRef = el)} /> with the following code




  <div style={{ display: "none" }}>
     <ComponentToPrint ref={(el) => (componentRef = el)} />
  </div>



Enter fullscreen mode Exit fullscreen mode

You should have the following screen now:
The free component screen with hidden print component

You will still get same result if you click the print button like mine below:

print dialogue with the print preview

Incredible!!!

IMPORTANT NOTICE!

The trigger component (PrintComponent in our case) can be either functional or class component but the component to be printed (ComponentToPrint in our case) must be a class component for it to work.

Conclusion

We have been able to see how to make printing in React very easy. Not just that we can print only the component we want, we can also hide the component and the CSS styles will not be affected.

There are a lot of other functionalities that we didn't touch but are available in the documentation. I encourage you to take your time and look into the documentation, play around with other functionalities and see what you can come up with.

All codes are here

Top comments (4)

Collapse
 
faisal_ali profile image
Faisal ali

Hi

I make an pdf patient report using react-to-print. when i see data in browser its fine but when i print it its alignment not remain same. Plz help me.

Thanks,
Faisal

Collapse
 
ravee_in profile image
Ravi Kumar

Hi Faisal,
To resolve your issue you need to create/add new stylesheet Print.css which will take care of your styling while printing.

media="print" is important

Collapse
 
edwsilva profile image
Edwsilva

Excellent article. Your explanations are very clear and have helped me a lot.

Collapse
 
alzter profile image
Alzter

This is awful! What an overcomplicated, indulgent way of printing things. Printing out the contents of a page should not require multiple classes, dependencies, and lines of code.