In this article, you can learn how to export an array of objects to an Excel file using a reusable React component.
Not so long ago, I was tasked with adding an export-array-to-excel button to some pages of a React application. The criteria given for this button was:
A screenshot of the export-array-to-excel component.
I found out that this is a common feature request (maybe with a little variation) given to developers, especially those who work on admin dashboard-like projects, and that is why I’m writing this article.
This article assumes that you have a fair knowledge of JavaScript and React. In this article, I will first show you the fundamental concepts involved in exporting an array of objects into an Excel sheet. Then, based on that, create the reusable export-array-to-excel component shown above, using Chakra UI as the component library of choice.
The first thing that needs to be figured out is how to prompt a download on the browser.
In plain HTML, creating a button to prompt a download in the browser is pretty straightforward using an anchor tag and its download attribute. Simply pass the URL or file path of the file to be downloaded to the href
attribute:
<a href="/files/excel-sheet-to-download.xls" download=”customer-list”>
<button> Download to excel </button>
</a>
The download
attribute is part of the HTML5 spec, and it specifies that the target should be downloaded when the link is clicked. The value passed to the download
attribute specifies the filename for the downloaded file.
Unfortunately, the solution above won’t exactly work for our use case because there isn’t a pre-existing Excel file to link to.
We’ll have to perform four tasks spontaneously when the download button is clicked:
Blob
and URL.createObjectURL()
methodshref
of an anchor tag with a download attribute, then programmatically click the anchor tag to prompt a downloadLet’s go over each step and write the necessary code for it. But first, we need to set up a React app and Chakra UI.
#react #excel #javascript #web-development