Reputation: 1021
I am making a simple resume generation app.
Index.js:
import ReactDOM from "react-dom";
import Resume from "../components/resume";
import React, { useRef } from "react";
import { useReactToPrint } from "react-to-print";
const App = () => {
const componentRef = useRef();
const handlePrint = useReactToPrint({
content: () => componentRef.current
});
return (
<div className="bg-gray-200 p-6">
<button
type="button"
className="bg-gray-500 border border-gray-500 p-2 mb-4"
onClick={handlePrint}
>
{" "}
Print Resume{" "}
</button>
<Resume ref={componentRef} />
</div>
);
};
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
The resume gets generated from the components/resume.js
file and it is a functional component..
I am using the react-to-print library to print the resume component alone.
Also took the reference from here ..
But in my application, If I click the Print Resume
, then the resume doesn't gets printed..
Instead I get the following warnings,
Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?
and another warning as,
For "react-to-print" to work only Class based components can be printed.
Complete Working Example:
https://codesandbox.io/s/tailwind-react-sandbox-forked-uivc8
Please try clicking the Print Resume
button in the above link where it doesn't print the resume.
Could you please help me to print the generated resume? Thanks in advance..
Upvotes: 3
Views: 18098
Reputation: 932
The component you want to print will still need to be a class component so I converted the Resume
component to a class component.
If you try using this as ref to pring <h1 ref={componentRef}>HELLO?</h1>
that will work even though a simple h1 tag is not class based component.
Try this on this edited sandbox of yours.
If you want a solid functional component you can migrate the Resume
component as the child of <div ref={componentRef} />
.
Upvotes: 2
Reputation: 14891
You just have to use React.forwardRef()
const Resume = React.forwardRef((props, ref) => {
// ...
return (
<div className="bg-gray-200 p-6" ref={ref}>
...
</div>
)
})
Forked codesandbox
Upvotes: 11