reactjstypescriptreact-to-print

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.


Solution

  • 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