How to create a csv file from response data in React

Last updated on Jan 20, 2022 by Suraj Sharma



In this tutorial, you’ll learn how you can create a csv file from async response data in React.

For this tutorial, we will use react-csv npm library.



Getting Started


react-csv is a popular open source library to generate and download csv files from a response data, with 149k+ weekly downloads.


Install react-csv


npm install --save react-csv


Create a new component


Create a <ExportCSV /> component, which will do two things,


1) It fetches reponse data from the fake api created using json-server,



//response

{
  "results": [
    {
      "id": 1,
      "userDetails": {
        "firstName": "Suraj",
        "lastName: "Sharma",
        "location": "India"
      },
      "status": "Active"
    },
    {
      "id": 2,
      "userDetails": {
        "firstName": "John",
        "lastName: "Smith",
        "location": "Brazil"
      },
      "status": "Inactive"
    }
  ]
}


2) Next, it generates a csv file using reponse data results and downloads the file.


// ExportCSV.jsx

import React, { useState, useEffect } from react;
import { CSVLink } from react-csv;

const ExportCSV = () => {

const { fileData, setFileData } = useState();

// json key should match the header's key

const [fileHeaders] = useState[{
  {label: 'ID', key: 'id'},
  {label: 'First Name', key: 'userDetails.firstName'},
  {label: 'Last Name', key: 'userDetails.lastName'},
  {label: 'Last Name', key: 'userDetails.lastName'},
  {label: 'Location', key: 'userDetails.location'},
  {label: 'Status', key: 'status'},
}]
};

const handleDataFetch = async() => {
  const response = await fetch('https://localhost:5000/results');
  const respJSON = await response.json();
  setFileData(respJSON)
};

useEffect(()=>{
  handleDataFetch();
}, [])

return (
  <div>
    <h3>Export to CSV</h3>
    {fileData?.length &&
      <CSVLink
        headers={fileHeaders}
        data={fileData}
        filename="results.csv"
        target="_blank"
      >
        Export
      </CSVLink>
    }
  </div>
);

export default ExportCSV;


react-csv exports CSVLink component, which accepts

  1. results stored in fileData state through data property,

  2. custom file name 'results.csv' through filename property, and

  3. csv headers stored in fileHeaders state through headers property



Call in App.js component


Now we will call the ExportCSV component in the App.jsx


// App.jsx
const App = () => {

  return (
    <ExportCSV />
  );
}

export default App;


Conclusion


In this tutorial, I have covered the basic usage of the react-csv library, that is to generate and download a csv file on click of a export link.

For advanced usages, you can visit react-csv examples



Related Solutions


Rate this post


Suraj Sharma is a Full Stack Software Engineer. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.