Print a div in React js or HTML – a Simple JavaScript function

Do you know how to print a div in react js or HTML?

Before I tell you how. I wanna tell you will I am creating this article. A few days ago i worked on a CRM project that has an invoice view option. my client needed an option to print the invoice.

I searched online and tried different methods. it was working with HTML but not with react js. so I modified the code and worked perfectly on reactjs. So I am sharing with you all the code also I am keeping that here as a document.

Create your page component and add this function into it

const Print = () =>{     
  //console.log('print');  
  let printContents = document.getElementById('printablediv').innerHTML;
  let originalContents = document.body.innerHTML;
  document.body.innerHTML = printContents;
  window.print();
 document.body.innerHTML = originalContents; 
}

Now we can create a printable div on the page.

<div  id='printablediv'>
    Print me
</div>

Now create a button to call the function



<button type="button" onClick={Print} > Print div</button>

yeah, that’s all .. you can generate a print from the specific div.

all the digital marketing experts told me to write a blog with more than 500 words. but my topics are simple so I don’t have too many words .. you just grab the code copy and paste .. (like all programmers do.)  😉

 

 

Post Your Questions on our forum

Post a question on Forum

Ajith Jojo Joseph

Self taught, dedicated young entrepreneur with many licensed products under his sleeve. Passionate about technology, business and excellence in general.

Share with your friends:

Leave a Reply

Your email address will not be published.

Export html table to excel, pdf, csv format using Datatable

Do you know how to export html table to excel, pdf, CSV, or excel format using Datatable? If you don’t […]

August 4, 2022

Instagram Hashtag API PHP and JavaScript Integration with RapidAPI

Do you know how to integrate Instagram Hashtag API with your website? In this tutorial, I will show you how […]

August 2, 2022

How to host React Application into Cpanel – Routes not working Htaccess fix

Do you know how to host react applications into Cpanel? After building your react application. you will get an index.html […]

July 28, 2022

How to get user Public IP Address using Javascript

Do you know how to get the user IP address using javascript? I will show you how. Today we are […]

July 27, 2022

Digital Marketing Toolkit

Get Free Access to Digital Marketing Toolkit. You can use all our tools without any limits

Get Free Access Now