How can I print only one component on click of a button.
I know this solution:
window.frames["print_frame"].window.focus(); window.frames["print_frame"].window.print(); $('.print_frame').remove();
But React doesn't want to work with a frame.
Any solutions? Thank you.
To show or hide another component on click in React: Set the onClick prop on an element. When the element is clicked, toggle a state variable that tracks if the component is shown. Conditionally render the component based on the state variable.
The React onClick event handler enables you to call a function and trigger an action when a user clicks an element, such as a button, in your app. Event names are written in camelCase, so the onclick event is written as onClick in a React app. In addition, React event handlers appear inside curly braces.
There is kind of two solutions on the client. One is with frames like you posted. You can use an iframe though:
var content = document.getElementById("divcontents"); var pri = document.getElementById("ifmcontentstoprint").contentWindow; pri.document.open(); pri.document.write(content.innerHTML); pri.document.close(); pri.focus(); pri.print();
This expects this html to exist
<iframe id="ifmcontentstoprint" style="height: 0px; width: 0px; position: absolute"></iframe>
The other solution is to use the media selector and on the media="print"
styles hide everything you don't want to print.
<style type="text/css" media="print"> .no-print { display: none; } </style>
Last way requires some work on the server. You can send all the HTML+CSS to the server and use one of many components to generate a printable document like PDF. I've tried setups doing this with PhantomJs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With