I'm using useRef to select a component and print it.
Here is the component:
import React, { useRef } from 'react';
import { useReactToPrint } from 'react-to-print';
const Details = ({ view }) => {
const componentRef = useRef();
const handlePrint = useReactToPrint({
content: () => componentRef.current
});
return (
<div className="order-details-section" ref={componentRef}>
<div className="return-an-issue-header">
<div className="return-an-issue-title"></div>
{view && (
<div className="print-items-container">
<p onClick={handlePrint}>click to print</p>
</div>
)}
</div>
</div>
);
};
export default Details;
It works fine but only for the current component which is a part from the whole page. I would like to print the parent component, or to pass it by the className.
Is it possible to do something like that? To get the parent component in useRef or to select it by class?
You can move the useReactToPrint
to the parent and pass on the handlePrint function as props to the child component if you want to access a ref of the parent and print it
const Details = ({ view, handlePrint}) => {
return (
<div className="order-details-section">
<div className="return-an-issue-header">
<div className="return-an-issue-title"></div>
{view && (
<div className="print-items-container">
<p onClick={handlePrint}>click to print</p>
</div>
)}
</div>
</div>
);
};
export default Details;
const Parent = () => {
const componentRef = useRef();
const handlePrint = useReactToPrint({
content: () => componentRef.current
});
return (
<div ref ={componentRef}>
<div>Some other content</div>
<Details view={...} handlePrint={handlePrint}/>
</div>
)
}