Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print React component on click of a button?

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.

like image 257
AndryName Avatar asked May 09 '15 02:05

AndryName


People also ask

How do you display a component on a button click in React?

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.

How do you call a component onClick in React?

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.


1 Answers

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.

like image 171
Emil Ingerslev Avatar answered Oct 13 '22 09:10

Emil Ingerslev