1import React from 'react';
2import Button from '../shared/Button';
3import data from '../constants/sampleMovieData';
4import DataTable from '../../src/index';
5
6// Blatant "inspiration" from https://codepen.io/Jacqueline34/pen/pyVoWr
7function convertArrayOfObjectsToCSV(array) {
8	let result;
9
10	const columnDelimiter = ',';
11	const lineDelimiter = '\n';
12	const keys = Object.keys(data[0]);
13
14	result = '';
15	result += keys.join(columnDelimiter);
16	result += lineDelimiter;
17
18	array.forEach(item => {
19		let ctr = 0;
20		keys.forEach(key => {
21			if (ctr > 0) result += columnDelimiter;
22
23			result += item[key];
24			
25			ctr++;
26		});
27		result += lineDelimiter;
28	});
29
30	return result;
31}
32
33// Blatant "inspiration" from https://codepen.io/Jacqueline34/pen/pyVoWr
34function downloadCSV(array) {
35	const link = document.createElement('a');
36	let csv = convertArrayOfObjectsToCSV(array);
37	if (csv == null) return;
38
39	const filename = 'export.csv';
40
41	if (!csv.match(/^data:text\/csv/i)) {
42		csv = `data:text/csv;charset=utf-8,${csv}`;
43	}
44
45	link.setAttribute('href', encodeURI(csv));
46	link.setAttribute('download', filename);
47	link.click();
48}
49
50
51const Export = ({ onExport }) => <Button onClick={e => onExport(e.target.value)}>Export</Button>;
52
53const columns = [
54	{
55		name: 'Title',
56		selector: row => row.title,
57		sortable: true,
58	},
59	{
60		name: 'Director',
61		selector: row => row.director,
62		sortable: true,
63	},
64	{
65		name: 'Year',
66		selector: row => row.year,
67		sortable: true,
68	},
69];
70
71export const ExportCSV = () => { 72 const actionsMemo = React.useMemo(() => <Export onExport={() => downloadCSV(data)} />, []); 73 74 return <DataTable title="Movie List" columns={columns} data={data} actions={actionsMemo} />; 75};
76 77export default { 78 title: 'Examples/Export CSV', 79 component: ExportCSV, 80};