skip to Main Content

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:

  • "react-to-print" did not receive a contentRef op…or a
    optional-content param pass to its callback."
  • "There is nothing to print".

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>
    </>
  )
};

2

Answers


  1. 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

    Login or Signup to reply.
  2. Have you found out a solution for it? I am facing the same issue.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search