0

I am trying to print ANTD table using ReactToPrint hook, everything seems to work fine, but I want to show some text on top of page before print. means I want to show some text for header purpose, when I am setting the visibility of header component true, its not print on first click, it shows on 2nd click, but I want to show the header on first click and when I print or cancel, header should be hide.

Please help me, Please hit print button two time to see the result in the below link.

https://codesandbox.io/s/usestate-not-updating-data-when-passing-from-parent-functional-component-using-r-forked-xuhnl

Thanks in Advance

1
  • While providing an external link is fine, your question should be self-contained and preferably not rely on external resources to be answered. Please add the relevant code to the question. Commented Oct 30, 2021 at 23:48

1 Answer 1

0

When the handlePrint function is called, the ref componentRef points to the previous version of the component. printHeaderVisible only becomes true at the time of the next render.

You can try to postpone the print call until the next render like this

const reactToPrintFunc = useReactToPrint({
  content: () => componentRef.current,

  onBeforeGetContent: () => setprintHeaderVisible(true),
  onAfterPrint: () => setprintHeaderVisible(false)
});

const handlePrint = () => {
  setTimeout(reactToPrintFunc, 0);
};

or do as advised in this issue

const handlePrint = useReactToPrint({
  content: () => componentRef.current,

  onBeforeGetContent: () => {
    return new Promise((resolve) => {
      setprintHeaderVisible(true);
      resolve();
    });
  },
  onAfterPrint: () => setprintHeaderVisible(false)
});
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.