Code Monkey home page Code Monkey logo

react-csv-reader's Introduction

react-csv-reader

npm version npm Node.js CI a11y axe TypeScript Support

React component that handles csv file input. It handles file input and returns its content as a matrix.

Docs: nzambello.github.io/react-csv-reader

You can try it out in the playground in the docs or in the demo on Codesandbox.

Installation

Install the package with either yarn or npm.

With yarn:

yarn add react-csv-reader

With npm:

npm install --save react-csv-reader

Usage

Basic usage:

import React, { Component } from 'react'
import ReactDOM from 'react-dom'
import CSVReader from 'react-csv-reader'

class App extends Component {
  ...

  render() {
    return (
      <CSVReader onFileLoaded={(data, fileInfo, originalFile) => console.dir(data, fileInfo, originalFile)} />
    )
  }
}

ReactDOM.render(<App />, document.getElementById('root'))

More complex example:

import React, { Component } from 'react'
import ReactDOM from 'react-dom'
import CSVReader from 'react-csv-reader'

class App extends Component {
  ...

  const papaparseOptions = {
    header: true,
    dynamicTyping: true,
    skipEmptyLines: true,
    transformHeader: header =>
      header
        .toLowerCase()
        .replace(/\W/g, '_')
  }

  render() {
    return (
      <CSVReader
        cssClass="csv-reader-input"
        label="Select CSV with secret Death Star statistics"
        onFileLoaded={this.handleForce}
        onError={this.handleDarkSideForce}
        parserOptions={papaparseOptions}
        inputId="ObiWan"
        inputName="ObiWan"
        inputStyle={{color: 'red'}}
      />
    )
  }
}

ReactDOM.render(<App />, document.getElementById('root'))

Parameters

Name Type Default Description
accept string .csv, text/csv File type accepted by file input.
cssClass string csv-reader-input A CSS class to be applied to the wrapper element.
cssInputClass string csv-input A CSS class to be applied to the <input> element.
cssLabelClass string csv-label A CSS class to be applied to the <label> element.
label string, element If present, it will be rendered in a <label> to describe input aim.
onFileLoaded function (required) The function to be called passing loaded results, see below.
onError function Error handling function.
parserOptions object {} PapaParse configuration object override
inputId string react-csv-reader-input An id to be applied to the <input> element.
inputName string react-csv-reader-input A name attribute to be applied to the <input> element.
inputStyle object {} Some style to be applied to the <input> element.
fileEncoding string UTF-8 Encoding type of the input file.
disabled boolean false Set input disabled attribute.
strict boolean false Throws error on onError if file type is different from accept.

onFileLoaded

When the file has been loaded, it will be parsed with PapaParse from a CSV formatted text to a matrix of strings or a list of objects (using header option). That parsed data is returned to the parent component with onFileLoaded function (it will be passed as an argument). The second argument to onFileLoaded will be an object with infos about loaded file.

// data: PapaParse.ParseResult.data
// fileInfo: IFileInfo
onFileLoaded: (data: Array<any>, fileInfo: IFileInfo, originalFile: File) => any

For type definitions, see here.

Testing

This packages uses jest for unit tests and snapshot testing.

To run the tests:

yarn test

Automated accessibility tests are run with jest-axe.

Contributions

Please follow our convention on commits format.

react-csv-reader's People

Contributors

9renpoto avatar adeel55 avatar alexandermarston avatar antoinegrandchamp avatar antonioguerra93 avatar cajotafer avatar cavallando avatar dependabot[bot] avatar garrettmac avatar huuums avatar jsdotcr avatar kulor avatar mahesh-krishnakumar avatar nzambello avatar piotrobrebski avatar proudust avatar rahgurung avatar simonvanherweghe 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  avatar

react-csv-reader's Issues

Remove file name

Hi @nzambello

I wonder is there anyways I can remove the filename (move it back to "No file chosen") after handling and submit the data.

Btw, thank you for a great csv reading component.

npm run build failed to compile

Describe the bug
I'm trying to compile my project for production, but the following error always occurs:
Unexpected token: punc ()) [./node_modules/react-csv-reader/dist/react-csv-reader.js:1,1264][\js\app-rede.js:51124,1285]
I'm using webpack in my project.

  • node v12.22.1
  • npm 7.14.0
  • composer 2.0.12
  • PHP ^7.0
  • Laravel ^5.5

is it possible to run onFileLoaded when I am manually adding the file using drop event

I am manually adding the file using Drag and Drop API, on the drop I am pointing the file to the input field but this doesn't trigger the onFileLoaded.
Code sample (this isn't the real react code) to manually adding the file using drop event:

function handleDroppedFile(evt) {
  evt.preventDefault();
  // since we use jQuery we need to grab the originalEvent
  var dT = evt.originalEvent.dataTransfer;
  var files = dT.files;
  if (files && files.length) {
    // we set our input's 'files' property
    $('#image-event')[0].files = files;
  }
}
$('#image-event-label').on({
    'drop': handleDroppedFile
  })

<label for="image-event" id="image-event-label">
        Drop a file here
</label>
<input type="file" name="image-event" id="image-event">

Css for "choose file" button

I tried applying css for button by using "cssClass", "cssInputClass" and "inputStyle" but it was changing the style of the file name but not of Button.

Support for xlsx input

This is one of the coolest framework I've work with. I like to suggest to support for xlsx.. I have 2 file (csv & xlsx) with the same content. Reading from csv I get :
image

reading from xlsx :
image

title/balloon help override

I really like the component and find it useful.

It would be great if I could override the balloon help that appears on hover for example it shows 'No file chosen'. If I could pass a title prop (or something similar) to be used as a title attribute it would be cool.

Thanks!

typescript definition are missing

I chose this library over others because majority of the code is written in typescript.
When I add this to my project it gives me error

Could not find a declaration file for module 'react-csv-reader'. '/home/apoorvmote/import-export/node_modules/react-csv-reader/dist/react-csv-reader.js' implicitly has an 'any' type.
  Try `npm install @types/react-csv-reader` if it exists or add a new declaration (.d.ts) file containing `declare module 'react-csv-reader';`ts(7016)

To recreate

  1. npx create-react-app csv-test --use-npm --template typescript
  2. npm i react-csv-reader
  3. In App.tsx just add this line import CSVReader from 'react-csv-reader'
    then you get the error mentioned above.

Add disabled option

Hi!

I think a good feature would be adding disabled prop for CSVReader.

It can be used like

<CSVReader onFileLoaded={this.handleUploadFile} disabled={validating} />

Cheers!

project is dead?

because very needed:

  1. onFileLoaded doesnt return data for second time
    #45

  2. add inputRef feature
    #61

and no answer for this issues from autor

[Problem]parserOptions is not woking

Hello,

I wanna use parserOptions to make the header as true, but it's not working. Can you give an example to show me how to handle it?

I try to parse 2 rows of the csv, but it also gives me all of them.

<CSVReader
      cssClass="react-csv-input"
      label="Select CSV with secret Death Star statistics"
      onFileLoaded={handleForce}
      parserOptions={{
        preview: 2
      }}
    />

React peer dependency version doesn't resolve for React 17 projects anymore

Describe the bug
Projects with React 17 fail to resolve peer dependencies.

To Reproduce
Steps to reproduce the behavior:

  1. Install react-csv-reader to a project using React 17.
  2. Observe error:

Screen Shot 2022-04-27 at 11 27 25 AM

Expected behavior
A clear and concise description of what you expected to happen.

Platform (please complete the following information):

  • OS: MacOS
  • Browser: Chrome

Additional context
This bug seems to originate at the most recent release in this commit, not sure why the peer dependency version was changed.

Translation?

Is your feature request related to a problem? Please describe.
Translation of strings

Describe the solution you'd like
Translatable strings

Describe alternatives you've considered
N/A

Additional context
This is pretty basic.

Accessing filename?

I've been trying to see if there's a way to access the name of the uploaded file? Doesn't seem to be anything about that in the docs or anywhere that I can find.

onFileLoaded doesnt return data for second time

Describe the bug and Reproduce
If the file loads the first time, the file has a duplicate header, it calls the onFileLoaded function, but the second load is the same file, it will not call the onFileLoaded function anymore.

Expected behavior
2nd time it still has to run into function onFileLoaded

Screenshots
If applicable, add screenshots to help explain your problem.

Platform (please complete the following information):

  • Browser Chrome
  • Version "react-csv-reader": "^3.0.6"

CSV file: https://drive.google.com/file/d/1QfDRRAzsHZ6P4IiXNq-pUNba2KkOQd3u/view?usp=sharing

My code:

const papaParseOptions = {
  header: true,
  dynamicTyping: true,
  skipEmptyLines: true,
  transformHeader(header) {
    return header
  }
};
        <CSVReader
              onFileLoaded={handleForce}
              parserOptions={papaParseOptions}
            />


  const handleForce = (data, fileInfo) => {
    console.log('data', data)
  };

how can I upload same edited file?

after I upload csv file, then I edit the same file with same name but different content and upload again. The handleChange method doesn't trigger. is there any way to upload same edited file? Thank you.

No support of React-csv-reader for React version 18

As I try upgrading my react version from 16 to 18, I seen in my console that react-csv-reader is not supported for react 18

Steps to reproduce the behavior:

  1. Upgrade react version in package.json
  2. npm install

Expected behavior
I expected to install react-csv-reader in react 18 as there is no mention anywhere in the documentation regarding react versions.

Screenshots
image

Please let me know when this react version support will be available as it is a breaking change for our product.

Casting fields as number

Hi,

All the fields are being cast. So, values like '02310' are imported as '2310'.
I'm not sure if this is the desired behavior, but I need to keep the original value.
Is there a way to do this?

Thank you,

onFileLoaded function error

Describe the bug
When the file is uploaded the first time it works perfectly but if we upload the file the second time without refreshing the page it does not go to the function passed to the onFileLoaded.

To Reproduce
Steps to reproduce the behavior:

  1. Upload the file once
  2. upload it the second time and you will get the bug
    Expected behavior
    The function should be called every time a new file is uploaded

Platform (please complete the following information):

  • OS: [e.g. Ubuntu]
  • Browser [e.g. chrome]

npm run build failed to compile in create-react-app project

Describe the bug
Getting failed to compile error when running npm run build.

error is failed to minify:
./node_modules/react-csv-reader/dist/react-csv-reader.js:1:1294

To Reproduce
Steps to reproduce the behavior:

  1. run “npm run build” in create-react-app project

Used node v13.11.0 npm v6.13.7

Filezie upload

whether this library can detect file size ?
thank you

Chrome showing error Warning: `value` prop on `input` should not be null

Hi, guys, i tried to see if there is any issue that has been created or google it but couldn't solve it.

Every time i load this CSV component I get following error in my chrome.

Warning: value prop on input should not be null. Consider using an empty string to clear the component or undefined for uncontrolled components.

Not sure how will it solve, but i guess if you have a value attribute with empty string instead of null then this error might go away.

How can I trigger click event without jQuery?

I have CSVReader component and a button. I want when I press the button, input of CSVReader will be clicked, so my code (use jQuery) is:
<button onClick={() => $('.csv-input').click()}>Trigger</button>

If I use ref property instead of jQuery, the code is:
<CSVReader ... ref={ref => this.csvInput = ref}/>
<button onClick={() => this.csvInput.click()}>Trigger</button>
But ref is not available, please add it to your module. Thank you so much!

Camel case naming convention

Hi,
is it possible to keep camel case naming convention (or any naming convention) during the parsing operation? My starting headers name are

username;email;firstName;lastName;enabled

but what I got is

{
  username: "username_test",
  email: "email_test",
  firstname: "firstname_test",
  lastname: "lastname_test",
  enabled: true
}

thanks.

Clearing selected file from the input field

What is the way for clearing the file name from the input field on click of Clear Button?

Tried this: document.querySelector('.csv-input').value = ' ';
Says Object is possibly null .

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.