I am trying to download csv file of table entries using react-csv.
But every time I try to follow the steps to download the data and export them to CSV format I get this error:
Data should be a "String", "Array of arrays" OR "Array of objects"
here is my code:
import React, { useEffect, useRef, useState } from "react";
import { CSVLink } from "react-csv";
export default function App() {
const [data, setdata] = React.useState("");
const [tableCellsData, setTableCellsData] = useState([]);
const csvLink=useRef()
const [bDownloadReady, setDownloadReady] = useState(false);
useEffect(() => {
if (csvLink && csvLink.current && bDownloadReady) {
csvLink.current.link.click();
setDownloadReady(false);
}
}, [bDownloadReady]);
const getUniqueKeyFromArrayIndex = (rowNum, columnNum) => {
return `${rowNum}-${columnNum}`;
};
const onChangeHandler = (e) => {
console.log(e.target.name, e.target.value);
setTableCellsData({
...tableCellsData,
[e.target.name]: e.target.value
});
};
const generateTable = () => {
let table = [];
for (let i = 0; i < 3; i++) {
let children = [];
for (let j = 0; j < 4; j++) {
children.push(
<td>
<input
name={getUniqueKeyFromArrayIndex(i, j)}
defaultValue=""
Value={data}
onChange={onChangeHandler}
/>
</td>
);
}
table.push(
<tr key={i}>
<td>{children}</td>
</tr>
);
}
return table;
};
const tabled=Object.keys(tableCellsData)
function clickHandler(actionType){
if (actionType === 'DOWNLOAD') {
setDownloadReady(true);
}
}
return (
<>
<table>{generateTable()}</table>
<button onClick={(e)=>clickHandler('DOWNLOAD')}>click</button>
<CSVLink
data={tabled}
filename="data.csv"
className="hidden"
ref={csvLink}
target="_blank" />
</>
);
}
This code:
const tabled=Object.keys(tableCellsData)
will produce an array of strings (keys). Following the error it looks like this format is not supported. You need to pass an array of objects or arrays, or a string, but an array of string its not supported