Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to let the user download data (CSV) in React?

I'm using React to create a PWA (meaning it should ideally be usable on mobile and in the browser). I have a button in my drawer (burger menu) that should let the viewer download a CSV file.

import ListItem from '@material-ui/core/ListItem';
import ListItemIcon from '@material-ui/core/ListItemIcon';
import ListItemText from '@material-ui/core/ListItemText';
// ... 

<ListItem
  button
  onClick={handleExport}
  className="drawer-export-contacts-button"
>
  <ListItemIcon>
    <ShareIcon />
  </ListItemIcon>
  <ListItemText primary={strings.exportContacts} />
</ListItem>

I have a function that prepares the CSV data as a Blob but I can't figure out how to trigger the download.

function handleExport() {
  const csv = convertContactsToCSV(contacts);
  const csvData = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
  // ...
}

How can you let the user download data?

like image 848
J. Hesters Avatar asked Dec 17 '22 17:12

J. Hesters


1 Answers

You can use FileSaver, which is a great tool to manage files on client-side.

Your code should look like this:

import FileSaver from 'file-saver';

function handleExport() {
  const csv = convertContactsToCSV(contacts);
  const csvData = new Blob([csv], { type: 'text/csv;charset=utf-8;' });

  FileSaver.saveAs(csvData, 'data.csv');
}
like image 68
l-portet Avatar answered Jan 01 '23 09:01

l-portet