React Logoreact-csv

React-csv is a lightweight and powerful React component that provides an easy way to generate and download CSV (Comma Separated Values) files directly from the client-side browser. It eliminates the need for server-side processing to create CSVs, making data export features quicker and more efficient in React applications.

Key features and benefits:

1. Client-Side Generation: All CSV generation happens in the user's browser, reducing server load and network requests.
2. Ease of Use: It offers a simple API with components like `CSVLink` and `CSVDownload` that are easy to integrate into any React component.
3. Flexible Data Handling: It can handle various data structures, typically an array of objects, and allows for custom headers.
4. Customization: Provides props for customizing filename, separator, target, and even allows asynchronous data loading.
5. No Server Dependency: Ideal for applications where simple data export is needed without complex backend logic.

Core Components:

* `CSVLink`: This component renders an anchor (`<a>`) tag or any custom component, which, when clicked, triggers the download of a CSV file. It takes `data`, `headers`, and `filename` as its primary props.
* `CSVDownload`: This component is used for programmatic or automatic CSV downloads. When rendered, it immediately initiates the download process. Useful for scenarios where the download should happen without explicit user interaction (e.g., after a form submission).

How it works:

You provide `react-csv` with an array of JavaScript objects as `data` and an optional array of objects for `headers` (defining the display label and the corresponding key in your data objects). The library then serializes this data into a CSV string, constructs a Data URI or Blob, and triggers a download via the browser's download mechanism. You can specify the `filename` for the downloaded file.

Example Code

import React from 'react';
import { CSVLink, CSVDownload } from 'react-csv';

const App = () => {
  const data = [
    { name: 'John Doe', email: 'john.doe@example.com', age: 30, city: 'New York' },
    { name: 'Jane Smith', email: 'jane.smith@example.com', age: 24, city: 'London' },
    { name: 'Peter Jones', email: 'peter.jones@example.com', age: 35, city: 'Paris' },
    { name: 'Alice Brown', email: 'alice.brown@example.com', age: 28, city: 'Berlin' }
  ];

  const headers = [
    { label: 'Full Name', key: 'name' },
    { label: 'Email Address', key: 'email' },
    { label: 'Age', key: 'age' },
    { label: 'City', key: 'city' }
  ];

  // Example for programmatic download (e.g., after some event)
  const [shouldDownload, setShouldDownload] = React.useState(false);

  const handleProgrammaticDownload = () => {
    // In a real application, you might fetch data or perform other actions
    // before triggering the download.
    setShouldDownload(true);
    // Reset after a short delay to allow download to complete, if needed
    setTimeout(() => setShouldDownload(false), 100);
  };

  return (
    <div>
      <h1>React CSV Export Example</h1>

      <h2>Download via Link/Button</h2>
      <CSVLink
        data={data}
        headers={headers}
        filename={'user_data.csv'}
        className='btn btn-primary'
        target='_blank'
      >
        Export Data to CSV (Click Me)
      </CSVLink>

      <h2 style={{ marginTop: '20px' }}>Programmatic Download</h2>
      <button onClick={handleProgrammaticDownload} className='btn btn-secondary'>
        Trigger Programmatic Download
      </button>

      {shouldDownload && (
        <CSVDownload
          data={data}
          headers={headers}
          filename={'programmatic_download.csv'}
          target='_blank'
        />
      )}

      <p style={{ marginTop: '30px', fontSize: '14px', color: '#666' }}>
        Note: For CSVLink, you'll see a 'user_data.csv' file downloaded.
        For the programmatic download, a 'programmatic_download.csv' will be downloaded shortly after clicking the button.
      </p>
    </div>
  );
};

export default App;