close

How to print React component on click of a button?

Hello Guys, How are you all? Hope You all Are Fine. Today we are going to learn How to print React component on click of a button? in javascript. So Here I am Explain to you all the possible methods here.

Without wasting your time, Let’s start This Article.

How to print React component on click of a button ?

  1. How to print React component on click of a button ?

    print React component on click of a button The other solution is to use the media selector and on the media="print" styles hide everything you don't want to print.

  2. print React component on click of a button

    print React component on click of a button The other solution is to use the media selector and on the media="print" styles hide everything you don't want to print.

Method 1


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.

Method 2


You’ll have to style your printout with @media print {} in the CSS but the simple code is:

export default class Component extends Component {

    print(){
        window.print();
    }


  render() {

  ...
  <span className="print"
              onClick={this.print}>
    PRINT
    </span>

  } 
}

Hope that’s helpful!

Summery

It’s all About this article. Hope all method helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which method worked for you? Thank You.

Leave a Comment