Reputation: 93
I am new to React js.
I am trying to export the returned tabular data to a csv file on a button click.
let names = [
{firstName: 'John',lastName: 'Cena'},
{firstName: 'Rey',lastName: 'Mysterio'},
]
const App = props => {
return (
<div>
{names.length > 0 && <table> //table renders only when array has elements
<tbody>
<tr>
<th>First Name</th> //setting headers
<th>Last Name</th>
</tr>
{names.map((name,index) => { //mapping for individual rows
return (
<tr key={index}>
<td>{name.firstName}</td>
<td>{name.lastName}</td>
</tr>
)
})}
</tbody>
</table>}
</div>
);
};
I want to create a button called export, and it should then download the table data thats being returned to a csv file.
Any help is greatly appreciated. Thanks.
Upvotes: 1
Views: 4471
Reputation: 482
A library like react-csv will help you to export data to a csv file easily, here is an example :
import { CSVLink, CSVDownload } from "react-csv";
let names = [
{firstName: 'John',lastName: 'Cena'},
{firstName: 'Rey',lastName: 'Mysterio'},
]
const App = props => {
return (
<>
<CSVLink data={names}>Download me</CSVLink>;
// or
<CSVDownload data={names} target="_blank" />;
</>
);
};
For more information about the library visit: https://www.npmjs.com/package/react-csv
Upvotes: 0