1

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.

1 Answer 1

0

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

Sign up to request clarification or add additional context in comments.

4 Comments

How do i return the same when someone uploads the file?
Can you explain more cuz this library is used only to export data in format csv
Sure, so lets say I have an upload button, when the user clicks on the upload file and uploads the file which we exported above, and when he uploads a file how do I display the same data in tabular format?
Ah okey, I understand your need. You can use another package to read csv file like react-papaparse or you can use this method explained in the article : dev.to/theallegrarr/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.