How to Create a Printable Component in React using react-to-print
By Kari Cheslock
May 30, 2022
1 min read
A printer
Subscribe

to this blog to receive future updates!

Hello, Happy Coders!

In this post I'm going to show you how to create a simple printable component that can be added to any website. The react-to-print package will create a pdf of any component. There are just a few tricks and tips for using it that I will show you here.

The first step is to install the react-to-print package using npm install react-to-print or yarn install react-to-print.

Next you will need to create a new component for your printable element. I have created an example printable component below that will print an image.

There are a couple of things to note here.

First of all, we are using the React hook useRef to reference our component. This reference is used in the ReactToPrint component that we are importing from the react-to-print package.

You will also see that I have created a button with some styling inside the ReactToPrint component. I styled this button using TailwindCSS classes, but you can use whatever you want.

Finally, I added the component I want print in a div element below the ReactToPrint element. I would recommend keeping the style tag when you are creating your own elements. This will allow you to switch between portrait and landscape for your print page orientation. Again, I styled the div containing the image with TailwindCSS classes.

Note the componentRef that is used throughout to create the component. Using this ref is how I have been able to get the react-to-print package to work effectively.

And that's all there is to it! Now, all you need to do is import the component you created, and it will be ready to go. I have imported the component I just created below. (Yes, that is a picture of my two adorable rescue dogs 😀.)

You will see if you click the button that you can now print this image to pdf.

Two adorable puppies in the backseat of a car

Please comment below 👇 or send me a message 📨 if you liked this post. You can also connect with me on LinkedIn .

Also, don't forget to Subscribe to this blog to receive future updates!

Happy Coding!

Kari


Sign in with Google to add a comment

Comments