uohman
uohman

Reputation: 37

Problems with using ReactToPrint to print a React component

I've been trying to use the ReactToPrint library to make a print button that makes it possible to print everything inside a div. In console I receive the errors:

When console logging componentRef.current I receive undefined in console, so it's clear that it doesn't access the ref, but I can't figure out why? Any suggestions?

This is my component:

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

export const StartPage = () => {

  const componentRef = useRef();
  const handlePrint = useReactToPrint({
    content: () => componentRef.current,
  });
  console.log(componentRef.current)

  return (
    <>
      <div ref={componentRef}>
        <HeaderText />
      </div>
      <button onClick={handlePrint}>Print</button>
    </>
  )
};

Upvotes: 2

Views: 940

Answers (3)

Uthpalavi Dias
Uthpalavi Dias

Reputation: 51

When I change the code as following I was success.

const printRef = useRef<HTMLDivElement>(null);    
const handlePrint = useReactToPrint({
    contentRef: printRef,
    documentTitle: `My_HeaderText_Print_${userId}`,
    onAfterPrint: () => console.log('Printing completed'),
  });
console.log(componentRef.current);

react-to-print version 3.0.4

Upvotes: 0

Agus Tinus
Agus Tinus

Reputation: 51

comment on https://github.com/MatthewHerbst/react-to-print/issues/742

try this

const handlePrint = useReactToPrint({
   documentTitle: 'Title',
   contentRef: componentRef,
})

Upvotes: 1

Rushil Mahadevu
Rushil Mahadevu

Reputation: 382

Make the ref with null:

const componentRef = useRef(null);

Use the ref attribute:

<div ref={componentRef}>

Full Version:

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

export const StartPage = () => {
  const componentRef = useRef(null);
  const handlePrint = useReactToPrint({
    content: () => componentRef.current,enter code here
  });

  return (
    <>
      <div ref={componentRef}>
        <HeaderText />
      </div>
      <button onClick={handlePrint}>Print</button>
    </>
  );
};

If there are still issues it might be a package problem

Upvotes: -1

Related Questions