Issue
So been trying to get this to work for a few days now, and am just not thinking of a solution. This is my first ReactJS project as I am more comfortable in C#.
Basically, I'm trying to create a print label component that will fire off the print dialog and print this printLabel component when the the link is clicked on the menu that calls this component. I can get this to work by having the component load in a drawer and mapping the trigger to an on-click event on a button, but I don't want the user to have to click an additional time.
import React, { useRef } from 'react';
import ReactToPrint from 'react-to-print';
class ComponentToPrint extends React.Component {
render() {
return (
<Col>
<Row>Customer Name</Row>
<Row>Address</Row>
<Row>City, State, Zip</Row>
</Col>
);
}
}
const PrintLabel = () => {
const componentRef = useRef();
return (
<div>
<ReactToPrint
trigger={() => <button>Print</button>}
content={() => componentRef.current}
/>
<ComponentToPrint ref={componentRef} />
</div>
);
};
export default PrintLabel;
Solution
It looks as though this behavior is not supported directly by react-to-print. One solution may be clicking the button (found by id) when the component renders. This can be done using the useEffect
hook (https://reactjs.org/docs/hooks-effect.html).
import React, { useRef, useEffect } from 'react';
...
const PrintLabel = () => {
const componentRef = useRef();
useEffect(() => {
document.getElementById('print-button').click();
});
return (
<div>
<ReactToPrint
trigger={() => <button id="print-button">Print</button>}
content={() => componentRef.current}
/>
<ComponentToPrint ref={componentRef} />
</div>
);
};
Answered By - Ed Lucas
Answer Checked By - - Marie Seifert (ReactFix Admin)