3

I am trying to figure out if there is any way I can download a csv file onClick of the EXPORT button on my webpage using react.

Here's what I have under component right now -

<div>
    <Button variant="contained" 
        size="small" 
        onClick={this.handleExport}>
        <SaveIcon label="Export" />
        Export
    </Button>
</div>

where handleExport generates a csv file using JSON data from backend.

I have tried to use react-csv, react-csv-downloader packages but none of them work for me.

Is there any way I can download the csv file onClick? Sample code would be greatly appreciated.

Thanks!

2
  • why the language tag spam? Commented Jul 4, 2019 at 18:42
  • The tags you have been using are not appropriate for this question. Please take the tour, review what are tags and how should I use them? and edit your post. Remember to at least read the mouseover on the tags you are using when asking a question. Commented Jul 4, 2019 at 18:43

1 Answer 1

8

I have this logic implemented. Code is very self explanatory.

    export function exportCSVFile(headers, items, fileTitle) {
      if (headers) {
        items.unshift(headers)
      }
    
      // Convert Object to JSON
      var jsonObject = JSON.stringify(items)
    
      var csv = convertToCSV(jsonObject)
    
      var exportedFilename = fileTitle + '.csv' || 'export.csv'
    
      var blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' })
      if (navigator.msSaveBlob) { // IE 10+
        navigator.msSaveBlob(blob, exportedFilename)
      } else {
        var link = document.createElement('a')
        if (link.download !== undefined) { // feature detection
          // Browsers that support HTML5 download attribute
          var url = URL.createObjectURL(blob)
          link.setAttribute('href', url)
          link.setAttribute('download', exportedFilename)
          link.style.visibility = 'hidden'
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link)
        }
      }
    }
Sign up to request clarification or add additional context in comments.

2 Comments

Ok but where the "convertToCSV" method comes from? it's a your custom function, an imported module... how can it be reproduced?
convertToCSV is just a function that converts json object to comma separated I guess. But indeed the answer is careless...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.