ivmarcos/react-to-pdf

Conditionally render an element

Closed this issue · 2 comments

Thank you @ivmarcos for creating this library - it's been a pleasure using it without having to write a whole lot of separate code.

I'm trying to conditionally render an element when I'm printing which is otherwise not displayed.

Here's an example for a watermark that I don't want to render on the screen, but want to show in the pdf:
https://codesandbox.io/p/sandbox/fervent-brown-2j55ld

Maybe TMI but my use case isn't exactly a watermark, it's a little bit more complex but I hope it represents the problem well!

Thanks

Hey @aaronzhongg I believe you can use the onclone callback to do that.

from the html2canvas docs: https://html2canvas.hertzen.com/configuration

Callback function which is called when the Document has been cloned for rendering, can be used to modify the contents that will be rendered without affecting the original source documen

See also: niklasvh/html2canvas#701 (comment)

import { Options } from 'react-to-pdf'
...
const options: Options = {
    overrides: {
      canvas: {
        onclone: (document) => {
          document.getElementById("elementId")!.classList.toggle('visible')
        },
      },
    },
  };

Thanks @ivmarcos that works well!