Git Product home page Git Product logo

react-csv-downloader's Introduction

React CSV Downloader

Renovate badge CircleCI Status Dependency Status devDependency Status

A simple react component to allow download CSV file from js object

Installation

npm install --save react-csv-downloader

Usage

Use with children component

import CsvDownloader from 'react-csv-downloader';
<CsvDownloader>
  <button>Download</button>
</CsvDownloader>;

Use without children component

<CsvDownloader text="Download" />

Datas

pass the downloaded datas as a component prop

const datas = [
  {
    cell1: 'row 1 - cell 1',
    cell2: 'row 1 - cell 2',
  },
  {
    cell1: 'row 2 - cell 1',
    cell2: 'row 2 - cell 2',
  },
];

<CsvDownloader datas={datas} />;

Datas (on demand with async function resolver)

pass a function to compute datas to be downloaded

const asyncFnComputeDate = () => {
  // do whatever you need async
  return Promise.resolve([
    {
      cell1: 'row 1 - cell 1',
      cell2: 'row 1 - cell 2',
    },
    {
      cell1: 'row 2 - cell 1',
      cell2: 'row 2 - cell 2',
    },
  ]);
};

<CsvDownloader datas={asyncFnComputeDate} />;

Column

pass the columns definition as a component prop to change the cell display name. If column isn't passed the cell display name is automatically defined with datas keys

const columns = [
  {
    id: 'cell1',
    displayName: 'Cell 1',
  },
  {
    id: 'cell2',
    displayName: 'Cell 2',
  },
];

<CsvDownloader columns={columns} />;

You can also use the columns definition to set the columns display order

Props

Name Type Default Required Description
columns array of object null false Columns definition
datas array of object/Func/Promise null true Downloaded datas or a Promise or a function that can resolve data on demand (async)
filename string null true You can pass the filename without extension. The extension is automatically added
extension string '.csv' false You can pass the file extension, note that it will affect filename
separator string ',' false Columns separator
noHeader boolean false false If true the header isn't added to the csv file
prefix string or boolean false false Filename prefix. If true prefix becomes a timestamp
suffix string or boolean false false Filename suffix/postfix. If true suffix becomes a timestamp
text string null false Download button text. Used if no children component.
wrapColumnChar string '' false Character to wrap every data and header value with.
bom boolean true false Activate or deactivate bom mode
newLineAtEnd boolean false false Insert new line at end of file.
disabled boolean false false If true the download process is blocked.
meta boolean false false If true the downloaded file will contain meta instruction sep to help microsoft excel and open office to recognize the sepator character.
handleError function undefined false Function to be invoked on error data
handleEmpty function undefined false Function to be invoked on empty result data
title string undefined false You can pass a string to be added as a title at the top of the sheet

All other props are passed to button or wrapping component.

Full example

pass the downloaded datas as a component prop

render() {
  const columns = [{
    id: 'first',
    displayName: 'First column'
  }, {
    id: 'second',
    displayName: 'Second column'
  }];

  const datas = [{
    first: 'foo',
    second: 'bar'
  }, {
    first: 'foobar',
    second: 'foobar'
  }];

  return (
    <div>
      <CsvDownloader
        filename="myfile"
        extension=".csv"
        separator=";"
        wrapColumnChar="'"
        columns={columns}
        datas={datas}
        text="DOWNLOAD" />
    </div>
  );
}

// content of myfile.csv
// 'First column';'Second column'
// 'foo';'bar'
// 'foobar';'foobar'

Get CSV contents

If you just need to get CSV contents, use import { toCsv } from 'react-csv-downloader'; to import toCsv function and use it directly.

License

MIT License

react-csv-downloader's People

Contributors

centrric-cntc0006 avatar dependabot[bot] avatar dolezel avatar dsounded avatar gcastl avatar gnunesmoura avatar greenkeeper[bot] avatar herbertpimentel avatar jnachtigall avatar leonadler avatar m14t avatar renovate[bot] avatar vivekitis avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

react-csv-downloader's Issues

React warning on usage of componentWillReceiveProps

react-dom.development.js:12050 Warning: componentWillReceiveProps has been renamed, and is not recommended for use. See https://fb.me/react-async-component-lifecycle-hooks for details.

  • Move data fetching code or side effects to componentDidUpdate.
  • If you're updating state whenever props change, refactor your code to use memoization techniques or move it to static getDerivedStateFromProps. Learn more at: https://fb.me/react-derived-state
  • Rename componentWillReceiveProps to UNSAFE_componentWillReceiveProps to suppress this warning in non-strict mode. In React 17.x, only the UNSAFE_ name will work. To rename all deprecated lifecycles to their new names, you can run npx react-codemod rename-unsafe-lifecycles in your project source folder.

Please update the following components: CSVLink

How do i pass the className or props to button container?

The problem is if you need to use flex container.

Example of Problem

margin-left style will not work in here.

<CsvDownloader>
   <Button style="margin-left: auto;">Export to CSV</Button>
</CsvDownloader>

Solution

Add custom props option.

<CsvDownloader style="margin-left: auto;">
   <Button>Export to CSV</Button>
</CsvDownloader>

Complicated Solution

<div style="margin-left: auto;">
   <CsvDownloader>
      <Button>Export to CSV</Button>
   </CsvDownloader>
</div>

Automatic Download

Is there a way to automatically download the CSV file after it is constructed?

Action required: Greenkeeper could not be activated 🚨

🚨 You need to enable Continuous Integration on all branches of this repository. 🚨

To enable Greenkeeper, you need to make sure that a commit status is reported on all branches. This is required by Greenkeeper because it uses your CI build statuses to figure out when to notify you about breaking changes.

Since we didn’t receive a CI status on the greenkeeper/initial branch, it’s possible that you don’t have CI set up yet. We recommend using Travis CI, but Greenkeeper will work with every other CI service as well.

If you have already set up a CI for this repository, you might need to check how it’s configured. Make sure it is set to run on all new branches. If you don’t want it to run on absolutely every branch, you can whitelist branches starting with greenkeeper/.

Once you have installed and configured CI on this repository correctly, you’ll need to re-trigger Greenkeeper’s initial pull request. To do this, please delete the greenkeeper/initial branch in this repository, and then remove and re-add this repository to the Greenkeeper App’s white list on Github. You'll find this list on your repo or organization’s settings page, under Installed GitHub Apps.

Recursive?

Is there a mode to deep publish the CSV? Currently only top-level fields are rendered in the CSV with '[object object]' in place of anything at a second level.

ESLint Error: import/no-unresolved

Summary

  • ESLint cannot resolve react-csv-downloader

Errors

{
  "code": {
    "target": {
      "$mid": 1,
      "authority": "github.com",
      "external": "https://github.com/benmosher/eslint-plugin-import/blob/v2.20.1/docs/rules/no-unresolved.md",
      "path": "/benmosher/eslint-plugin-import/blob/v2.20.1/docs/rules/no-unresolved.md",
      "scheme": "https"
    },
    "value": "import/no-unresolved"
  },
  "endColumn": 49,
  "endLineNumber": 8,
  "message": "Unable to resolve path to module 'react-csv-downloader'.",
  "owner": "eslint",
  "resource": "/path/to/file.js",
  "severity": 8,
  "source": "eslint",
  "startColumn": 27,
  "startLineNumber": 8
}

Accept undefined or null in the data attribute, and not process the csv in these cases.

I'm passing the data to the CsvDownloader component through an async function that fetches the data remotely. However, if I got an error from the server while fetching the data, I don't have anything to return to the component, so it returns undefined, and it gives an error on the CsvDownloader component.

It would be great if it accepts undefined to mean that we don't want to process the csv.

Thank you.

format cell size

is there a way to format the cell size according to the size of the content? or it is just possible by editing the document?

Only compute data when download button is pressed

At the moment this component (and hence its datas and columns structures) renders whenever it is in view. It would be better if these computations would only happen when the download button is pressed. Is this possible?

An in-range update of react is breaking the build 🚨

There have been updates to the react monorepo:

    • The dependency react was updated from 16.6.1 to 16.6.2.
  • The dependency react-dom was updated from 16.6.1 to 16.6.2.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

This monorepo update includes releases of one or more dependencies which all belong to the react group definition.

react is a direct dependency of this project, and it is very likely causing it to break. If other packages depend on yours, this update is probably also breaking those in turn.

Status Details
  • ci/circleci: install: Your tests failed on CircleCI (Details).

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Seperator

String Value of Object with ',' for example,
{"address": "14,Second Street ,Suite 700 San Jose, CA"}
Each word before the following ',' in the string is also separated into different columns.

Sourcemap warning with webpack 5

hi,

I'm getting this warning:

WARNING in ./node_modules/react-csv-downloader/dist/esm/index.js
Module Warning (from ./node_modules/source-map-loader/dist/cjs.js):
Failed to parse source map from 'node_modules/react-csv-downloader/src/index.tsx' file: Error: ENOENT: no such file or directory, open 'node_modules/react-csv-downloader/src/index.tsx'

it's only happening on react-csv-downloader, so I guess it has some relation

null values not being handled as expected

Greetings,
I am using your toCSV function for csv blob generation.
It has come to my notice that null values are being converted to 'null' string instead of ''.

I checked the internal code and I think I found the reason:
In src/lib/csv.ts, you have the function createChunkProcessor:
Line 86:
typeof v[k] !== 'undefined' ? v[k] : ''

Maybe you could change it to:
typeof v[k] !== 'undefined' && v[k] ? v[k] : ''

Optional extension e.g. txt

Hello, thanks for the library!

I'd like to know if there a way to export a file with .txt extension instead of .csv

No control over datetime field format

If one of the cells is a datetime field in the format MM-DD-YYYY h:mm a, it keeps formatting it as M/D/YY H:mm.
For example:
04-20-2018 4:20 pm ---> 4/20/18 16:20

Is there any way I can have it not change the data?

CSV Content function not being imported in Typescript

Hello,
I tried importing 'react-csv-downloader/dist/lib/csv' and using it directly.

However, the path does not seem to be present. Getting the following error:
"Cannot find module 'react-csv-downloader/dist/lib/csv' or its corresponding type declaration"

Edit:
I found the csv function in the following path
'react-csv-downloader/dist/cjs/lib/csv'

Please consider updating the doc

Handle error when datas is a promise

it would be nice to have a way to handle errors when datas is a promise that gets rejected.
Currently if there's nothing resolved, there's an error caused by trying to reduce an undefined result

Action Required: Fix Renovate Configuration

There is an error with this repository's Renovate configuration that needs to be fixed. As a precaution, Renovate will stop PRs until it is resolved.

Error type: undefined. Note: this is a nested preset so please contact the preset author if you are unable to fix it yourself.

Does not respect the order of the header

Hi
const columns = [
{ displayName: 'First', id: '1' },
{ displayName: 'Second', id: '1' },
{ displayName: 'Third', id: '3' }
]

If the information arrives [Third, Second, First] (axios), it is displayed in this way.
Expected result:
[First, Second, Third]

The header should order the order of the columns in the csv file

`datas` prop type errors when passing values that aren't strings

Hiya!

In TypeScript, the CsvDownload component compiles and runs as intended when passing in an object such as the following:

type Thing = {
  id: number;
  name: string;
  birthday: Date;
};

const things: Thing[] = [
  {
    id: 12,
    name: "Bob",
    birthday: new Date(2000, 5, 14),
  },
  {
    id: 69420,
    name: "Tim",
    birthday: new Date(1998, 8, 23),
  },
];

However, I get the following type error in my IDE:

No overload matches this call.
  Overload 1 of 2, '(props: ICsvDownloadProps | Readonly<ICsvDownloadProps>): CsvDownload', gave the following error.
    Type 'Thing[]' is not assignable to type 'Datas | (() => Datas) | (() => Promise<Datas>) | Promise<Datas>'.
      Type 'Thing[]' is not assignable to type 'Datas'.
        Type 'Thing' is not assignable to type 'string[] | { [key: string]: string | null | undefined; }'.
          Type 'Thing' is not assignable to type '{ [key: string]: string | null | undefined; }'.
            Property 'id' is incompatible with index signature.
              Type 'number' is not assignable to type 'string'.
  Overload 2 of 2, '(props: ICsvDownloadProps, context: any): CsvDownload', gave the following error.
    Type 'Thing[]' is not assignable to type 'Datas | (() => Datas) | (() => Promise<Datas>) | Promise<Datas>'.ts(2769)

Because datas is expecting string | null | undefined, whereas it should allow anything that can be converted to a string (i.e. string | number | boolean | symbol | object | null | undefined).

Unless I'm missing something silly, I think it should be changed in this line to suit:

export type Datas = (string[] | { [key: string]: string | null | undefined })[]

add costume style to report

Hi,
I use this package in my project. it is great and useful. thankyou very much for this package. but, how we add some costume style in report?

Package should not require react-hot-loader to run

When installing with yarn add on a app created with create-react-app, I get the following error:

Error: ENOENT: no such file or directory, open '.../node_modules/react-hot-loader/index.js'

Error goes away if I add react-hot-loader, but I'm not it's actually needed for the core functionality of the package.

filename suffix is not `YYYYMMDDhhiiss`

In my case the filename suffix is myfile_1586349856967.csv for

    <CsvDownloader
      filename="myfile"
      separator=";"
      suffix={true}
      columns={columns}
      datas={products}
    >

but the README says the suffix should be YYYYMMDDhhiiss. Should it not start with 2020 for YYYY then.

Besides, an ISO time code would be better, e.g.: 2020-04-08T15:04:11Z. https://en.wikipedia.org/wiki/ISO_8601 But that's another issue.

Thanks for the component, besides this it works pretty great :)

Upgrade to React v18 dependencies error

Hi all,
founded the issue when upgrading React to the last version released (v18). This is the stacktrace:

npm ERR! node_modules/react npm ERR! react@"^18.0.0" from the root project npm ERR! npm ERR! Could not resolve dependency: npm ERR! peer react@"^16.6.3 || ^17.0.0" from [email protected] npm ERR! node_modules/react-csv-downloader npm ERR! react-csv-downloader@"^2.7.1" from the root project

I know I can use
--legacy-peer-deps
during the installation (maybe this workaround cannot works for all people) but I think will be better to have a clean installation.

It's in your roadmap? Thanks to all team members.

Big Data freezes

Can u split generate csv file on chunk and work with "nextTick" (requestAnimationFrame/setTimeout).
If I want save csv with (about) 50k lines my browser freezes and I must wait....

extra column when passing in comma ',' or \r\n

I have an string for address like this '5 Example Street, Example Town, Example Country', the output csv will produce 3 seperate columns instead of one. The same goes if the string is '5 Example Street\r\nExample Town\r\nExample Country'.

In the end I resolved to using react-csv...

API denifition for meta data

hey man, I want to push one little more change for your code. But I want to ask your opinion about how do you prefer it to look like.

I am taking about metadata in the result csv file;

in my scenario it is extremelly important to add the meta "sep=," to make microsof excel and open office auto recognize the columns.

Check it:
https://superuser.com/questions/773644/what-is-the-sep-metadata-you-can-add-to-csvs

we can do that like so:

  1. add a meta boolean property as default false

When true It will then check for the separator definition and add the properly meta line in the text file; but this will be limited to sep metadata

  1. we may add meta property as string[] and just output in the file whatever the user defined into it.

LMK if this makes sense for your. It will be really really helpful for my case.

Add prop to enable a carriage return at the end of the file

Hi, great component, works very well!

Would it be possible to add an option to have an extra line at the end of the file?

It seems trivial but I have a case where a BACS file is only accepted with a trailing line.

e.g. Before:

123456,Hello,world

e.g. After:

123456,Hello,world

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Awaiting Schedule

These updates are awaiting their schedule. Click on a checkbox to get an update now.

  • Update all non-major dependencies (@types/node, mocha)

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Detected dependencies

circleci
.circleci/config.yml
  • node 5.2.0
github-actions
.github/workflows/codeql-analysis.yml
  • actions/checkout v4
  • github/codeql-action v3
  • github/codeql-action v3
  • github/codeql-action v3
npm
example/package.json
  • react 18.3.1
  • react-dom 18.3.1
  • react-scripts 5.0.1
package.json
  • file-saver ^2.0.2
  • @types/chai 4.3.17
  • @types/file-saver 2.0.7
  • @types/mocha 10.0.7
  • @types/node 20.14.14
  • @types/react 18.3.3
  • @typescript-eslint/eslint-plugin 7.18.0
  • @typescript-eslint/parser 7.18.0
  • chai 4.5.0
  • eslint 8.57.0
  • eslint-config-prettier 9.1.0
  • eslint-plugin-import 2.29.1
  • eslint-plugin-prettier 5.2.1
  • eslint-plugin-react 7.35.0
  • eslint-plugin-react-hooks 4.6.2
  • eslint-plugin-sonarjs 0.25.1
  • mocha 10.7.0
  • prettier 3.3.3
  • react 18.3.1
  • rimraf 5.0.10
  • ts-node 10.9.2
  • typescript 5.5.4
  • react ^16.6.3 || ^17.0.0 || ^18.0.0
  • npm >=7.0.0

  • Check this box to trigger a request for Renovate to run again on this repository

Download not working on Mozilla

I'm using your module and found this line of code that isn't compatible with Mozilla.
at file react-csv-downloader/src/index.js line 86
a.click();

After changing that line to
a.dispatchEvent(new MouseEvent("click", { "view": window, "bubbles": true, "cancelable": false }));
it was fixed.

Can't export more than 2 by 2 csv

I am working on a react typescript electron project and I'm using react-cvs-downloader to export some queried data. I've been able to export to a csv file when the data is 2 by 2.

This is my component

return(
      <CsvDownloader
        filename={'foobar'}
        prefix={false}
        suffix={false}
        separator=","
        wrapColumnChar=""
        datas={datas}
      />)

Download works fine when datas is

const datas = [
    ["foo", "bar"],
    ["foobar", "foobar"],
  ];


But with a bigger data set it doesn't
ie.
const datas2 = [
    ['hi', 'jo','hi', 'jo','hi', 'jo','hi', 'jo','hi', 'jo','hi', 'jo',],
    ['hi', 'jo','hi', 'jo','hi', 'jo','hi', 'jo','hi', 'jo','hello', 'bob'],
    ['hi', 'jo','hi', 'jo','hi', 'jo','hi', 'jo','hi', 'jo','for me?', 'yes'],
    ['hi', 'jo','hi', 'jo','hi', 'jo','hi', 'jo','hi', 'jo','hi', 'jo'],
    ['hi', 'jo','hi', 'jo','hi', 'jo','hi', 'jo','hi', 'jo','hello', 'bob'],
    ['hi', 'jo','hi', 'jo','hi', 'jo','hi', 'jo','hi', 'jo','for me?', 'yes'],
    ['hi', 'jo','hi', 'jo','hi', 'jo','hi', 'jo','hi', 'jo','hi', 'jo'],
    ['hi', 'jo','hi', 'jo','hi', 'jo','hi', 'jo','hi', 'jo','hello', 'bob'],
    ['hi', 'jo','hi', 'jo','hi', 'jo','hi', 'jo','hi', 'jo','for me?', 'yes'],
    ['hi', 'jo','hi', 'jo','hi', 'jo','hi', 'jo','hi', 'jo','hi', 'jo'],
    ['hi', 'jo','hi', 'jo','hi', 'jo','hi', 'jo','hi', 'jo','hello', 'bob'],
    ['hi', 'jo','hi', 'jo','hi', 'jo','hi', 'jo','hi', 'jo','for me?', 'yes'],
    ['hi', 'jo','hi', 'jo','hi', 'jo','hi', 'jo','hi', 'jo','hi', 'jo'],
    ['hi', 'jo','hi', 'jo','hi', 'jo','hi', 'jo','hi', 'jo','hello', 'bob'],
    ['hi', 'jo','hi', 'jo','hi', 'jo','hi', 'jo','hi', 'jo','for me?', 'yes'],
    ['hi', 'jo','hi', 'jo','hi', 'jo','hi', 'jo','hi', 'jo','hi', 'jo'],
    ['hi', 'jo','hi', 'jo','hi', 'jo','hi', 'jo','hi', 'jo','hello', 'bob'],
    ['hi', 'jo','hi', 'jo','hi', 'jo','hi', 'jo','hi', 'jo','for me?', 'yes'],
    ['hi', 'jo','hi', 'jo','hi', 'jo','hi', 'jo','hi', 'jo','hi', 'jo'],
    ['hi', 'jo','hi', 'jo','hi', 'jo','hi', 'jo','hi', 'jo','hello', 'bob'],
    ['hi', 'jo','hi', 'jo','hi', 'jo','hi', 'jo','hi', 'jo','for me?', 'yes'],
    ['hi', 'jo','hi', 'jo','hi', 'jo','hi', 'jo','hi', 'jo','hi', 'jo'],
    ['hi', 'jo','hi', 'jo','hi', 'jo','hi', 'jo','hi', 'jo','hello', 'bob'],
    ['hi', 'jo','hi', 'jo','hi', 'jo','hi', 'jo','hi', 'jo','for me?', 'yes'],
    ['hi', 'jo','hi', 'jo','hi', 'jo','hi', 'jo','hi', 'jo','hi', 'jo'],
    ['hi', 'jo','hi', 'jo','hi', 'jo','hi', 'jo','hi', 'jo','hello', 'bob'],
    ['hi', 'jo','hi', 'jo','hi', 'jo','hi', 'jo','hi', 'jo','for me?', 'yes'],
  ];

I was able to get it working by changing a line in the processChunk function at line 89
from

if (i < chunk.length - 1) 

to

if (i < chunks.length - 1)

idk if that's what should be happening, but wanted to shoot a heads up.

Implement "onSuccess" and "onError" type props?

Feature request. I would love to run code based on either successful CSV generation/download or not. I see that handleClick is currently an async function, but I am not seeing a straight forward way via props to tap into that.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.