Axel León
Axel León

Reputation: 476

How to use react-to-print with TypeScript?

I usually use react-to-print (https://www.npmjs.com/package/react-to-print) for printing React components with a low effort and great flexibility. I'm starting to write my applications with TypeScript, and this is the first time I need to combine these two things.

This is my code:

<ReactToPrint
  trigger={() => <Button variant="contained" color="primary">Generar</Button>}
  content={() => componentRef.current}
/>
<PrintableComponent ref={componentRef} />

To create the reference, I simply do:

const componentRef = useRef();

In JavaScript, it works, but when I use .tsx, I get an error in the "content" parameter of the ReactToPrint component and another in the ref parameter of my own PrintableComponent. Could someone help me with this?

Basically, the errors say that the interfaces do not match.

Upvotes: 10

Views: 12349

Answers (3)

Uthpalavi Dias
Uthpalavi Dias

Reputation: 51

enter image description hereThis is my working code

import the necessary libraries as bellow for the .tsx file.

import React, { useRef } from 'react';
import { useReactToPrint } from 'react-to-print';

Create necessary button,

<Button
    variant="contained"
    color="primary"
    onClick={() => handlePrint && handlePrint()} // Wrap the call in an anonymous function
>
Print Profile
</Button>

Creat the function,

const printRef = useRef<HTMLDivElement>(null); // Ref for printable content

const handlePrint = useReactToPrint({
    contentRef: printRef,
    documentTitle: `Principal_Profile_${ttUserId}`,
    onAfterPrint: () => console.log('Printing completed'),
});

After these steps I was success and was able to print the content in the typescript file as I needed.

Upvotes: 1

tiny_mike
tiny_mike

Reputation: 297

You can define the type for useRef to get rid of the ts error credit to shane935:

const componentRef = useRef<HTMLDivElement>(null)

And if you, like me, are using functional components you will get a problem trying to use that ref following react-to-print class based components. To bypass this error you can wrap your component you wish to print in a div:

<ReactToPrint
  trigger={() => <Button variant="contained" color="primary">Generar</Button>}
  content={() => componentRef.current}
/>
<div ref={componentRef}>
  <PrintableComponent />
</div>

Everything inside this div will be printed.

Upvotes: 13

mirage
mirage

Reputation: 708

Seems like a known issue when using hooks: https://github.com/gregnb/react-to-print/issues/214

As an alternative, you can avoid the useRef hook and follow the example in the source repo which seems to work in TypeScript:

https://github.com/gregnb/react-to-print/blob/master/example/index.tsx

i.e., the first example on the npm readme doc: https://www.npmjs.com/package/react-to-print#example

Upvotes: 4

Related Questions