How to use react-to-print with TypeScript?

10.1k Views Asked by At

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.

2

There are 2 best solutions below

0
On BEST ANSWER

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

0
On

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.