Printing in React Made Easy With React-To-Print
Tags: react, tutorial, beginners, javascript
Published: 2021-08-30 07:23:52

## 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](https://www.npmjs.com/package/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](https://developer.mozilla.org/en-US/docs/Web/JavaScript) and [React](https://reactjs.org/) especially the [difference between class and functional component](https://reactjs.org/docs/components-and-props.html).

## Starter project
We will be using the app we [created here](https://dev.to/ebereplenty/full-stack-authentication-and-hosting-nodejs-reactjs-heroku-netlify-3fcm) as the starter project of this tutorial. To get the project setup in your local machine, do the following:

* Clone the [repo](https://github.com/EBEREGIT/react-auth)
```javascript

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

```

* Install the dependencies
```javascript

npm install

```

* 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>
    </>
  );
}

```
> 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:

```javascript

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>
    );
  }
}

```

* Add the following styles in the ``index.css``

```css

thead th {
  padding-right: 50px;
}

```

* Render the component in the ``freeComponent.js`` file like so:

```javascript

<PrintComponent />

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

import PrintComponent from "./PrintComponent";

```

* Now, navigate to ``http://localhost:3000/free`` and you should have the following screen:

![Screen with Print component](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xjnlrcx3ev7ln7vja0kr.JPG)

* When you click on the blue button, you should have the print dialogue with the print preview
![print dialogue with the print preview](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ele9hm5mxw5w0442y6hn.JPG)
*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

```javascript

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

```
> You should have the following screen now:
![The free component screen with hidden print component](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fni57zc095kuen9xmd6o.JPG)

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

![print dialogue with the print preview](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ele9hm5mxw5w0442y6hn.JPG)

*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](https://github.com/EBEREGIT/react-auth/tree/print-tutorial![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1nuu0ec3k5cjj2wqw6zg.png)
 )