Welcome folks today in this blog post we will be downloading csv file
in browser using array of objects
or json data
using react-csv
library in Javascript. All the full source code of the application is shown below.
Get Started
In order to get started you need to make a new react.js
app using the below command
npx create-react-app sampleapp
cd sampleapp
And after that you need to install the below libraries using the npm
command as shown below
npm i react-csv
And after that you will see the below directory
structure of the react.js app as shown below
And now you need to copy paste the below code inside the App.js
file as shown below
App.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
import React, { Component } from 'react'; import { render } from 'react-dom'; import { CSVLink, CSVDownload } from "react-csv"; import { csvData } from './Data' import './style.css'; class App extends Component { constructor() { super(); this.state = { name: 'React' }; } render() { const headers = [ { label: "First Name", key: "firstname" }, { label: "Last Name", key: "lastname" }, { label: "Email", key: "email" } ]; const data = [ { firstname: "Ahmed", lastname: "Tomi", email: "ah@smthing.co.com" }, { firstname: "Raed", lastname: "Labes", email: "rl@smthing.co.com" }, { firstname: "Yezzi", lastname: "Min l3b", email: "ymin@cocococo.com" } ]; console.log(csvData.length) return ( <div> <CSVLink data={csvData} filename={"burnit.csv"}>Download CSV</CSVLink> <CSVLink data={data} headers={headers} filename={"headers.csv"}>Download CSV</CSVLink> </div> ); } } render(<App />, document.getElementById('root')); |
As you can see we are importing the react-csv
library at the top and then we are using the CSVLink
directive to pass the data
into it and then we are also giving the filename
of the csv file and then we are also downloading the csv
file as an attachment.