vkt
vkt

Reputation: 1459

React js create a download file from a json response from API

I have a react js app that is receiving the following JSON object from the API. How can I create a CSV file export from the JSON and create a download link for the user using react js?

{
    "data": [
        {
            "location": "232323",
            "name": "ZZZZZZZ",
            "phoneNumber": "2003223232"
        },
        {
            "location": "23334",
            "name": "XYZ",
            "phoneNumber": "1234323334"
        }
}

I am newbie to the react.js

Upvotes: 2

Views: 2918

Answers (1)

Muhammad Ali
Muhammad Ali

Reputation: 695

You can use react-json-to-csv library for this purpose. Add the library using:

yarn add react-json-to-csv

Then use it like this:

import React from "react";
import CsvDownload from "react-json-to-csv";

import data from "./data.json"; // or you can use a file from api

const mockData = data;

export default function () {
  return (
    <div>
      <CsvDownload data={mockData.data}>Json to CSV</CsvDownload>
    </div>
  );
}

You data file i.e data.json will be:

{
  "data": [
    {
      "location": "232323",
      "name": "ZZZZZZZ",
      "phoneNumber": "2003223232"
    },
    {
      "location": "23334",
      "name": "XYZ",
      "phoneNumber": "1234323334"
    }
  ]
}

By pressing the button you can download the file.

Upvotes: 3

Related Questions