Code Monkey home page Code Monkey logo

react-files's Introduction

React Files

A minimal, zero dependency, file input (dropzone) component for React.

If upgrading from version 1 or 2, see the Upgrading to Version 3 section below.

Alt text

Installation

Install using npm or yarn. Requires React 16.8+.

npm install react-files --save

Basic Usage

import React from 'react'
import Files from 'react-files'

const FileDropzone = () => {
  const handleChange = (files) => {
    console.log(files)
  }

  const handleError = (error, file) => {
    console.log('error code ' + error.code + ': ' + error.message)
  }

  return (
    <div className="files">
      <Files
        className='files-dropzone'
        onChange={handleChange}
        onError={handleError}
        accepts={['image/png', '.pdf', 'audio/*']}
        multiple
        maxFileSize={10000000}
        minFileSize={0}
        clickable>
        Drop files here or click to upload
      </Files>
    </div>
  )
}

Upgrading to Version 3

Most of the changes made to version 3 are internal, but there are some notable and breaking changes:

  1. The most significant change is that react-files no longer manages state internally to track files that have been uploaded to a file list. This can be achieved quite simply however - please refer to the ListWithUpload example.
  2. dropActiveClassName prop has been renamed to dragActiveClassName.
  3. Removed unnecessary parent/wrapper div element. No more default values for className or dragActiveClassName props.
  4. Ability to pass in a render prop with a prop that indicates whether a drag is in progress. See the RenderProps example.
  5. Ability to pass in attributes to underlying input

For a full list of changes, please checkout the v3.0.0 release changelog or the corresponding pull request.

Props

onChange(files) - Function

Perform work on files added when submit is clicked.


onError(error, file) - Function

  • error.code - Number
  • error.message - String

Perform work or notify the user when an error occurs.

Error codes are:

  1. Invalid file type
  2. File too large
  3. File too small
  4. Maximum file count reached

accepts - Array of String

Control what types of generic/specific MIME types or file extensions can be dropped/added.

See full list of MIME types here: http://www.iana.org/assignments/media-types/media-types.xhtml

Example:

accepts={['image/*', 'video/mp4', 'audio/*', '.pdf']}

multiple - Boolean

Default: true

Allow multiple files


clickable - Boolean

Default: true

Dropzone is clickable to open file browser. Disable for dropping only.


maxFiles - Number

Default: Infinity

Maximum number of files allowed


maxFileSize - Number

Default: Infinity

Maximum file size allowed (in bytes)


minFileSize - Number

Default: 0

Minimum file size allowed (in bytes)


dragActiveClassName - String

Class added to the Files component when user is actively hovering over the dropzone with files selected.


Examples

To run the examples locally, clone and install peer dependencies (React 16.8+)

git clone https://github.com/mother/react-files
npm install
npm i react react-dom

Then run the examples server:

npm run examples

Then visit http://localhost:8080/

License

MIT. Copyright (c) Mother Co. 2023

react-files's People

Contributors

asabhaney avatar jaredreich avatar marcosrjjunior avatar seymourisdead avatar wootencl 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  avatar  avatar

react-files's Issues

can't open file greater than 10MB

Even if i set maxFileSize={9 999 999 999} i can't include files grather than 10 000 000B. Even if a don't specific tha variable. Why?

Maximum file count reached

I have set maximum file count to 1. But when I add an image and then remove it and then add it again it shows Maximum file count reached error. How to set reset the File Count to 0?

div wrapper css class

Hey.
It would be nice if you gave an option to add a class to the surrounding div.
I encountered a problem when doing custom CSS on .files-dropzone with flexbox and saw that I couldn't add CSS to the surrounding div.
screenshot_1

Dependency upgrades

Do you have plans to upgrade the peerDependency react in packages.json?

I would like to get rid of this warning when running my project:

warning "[email protected]" has incorrect peer dependency "react@^15.0.0 || ^16".

Cheers

Cannot accept files without an extension

I was trying out this component to drop DICOM files. While they are typically associated with the .dcm extension, it is also common for the files not to specify an extension at all (e.g. the file name being just I_00001). In these cases, while the media type is still application/dicom, they will not show up on the file upload form when accepting only this type, and even when selecting them here or dropping them
to the drop zone, they will be always excluded with the error "I_00001 is not a valid file type" (code 1) if they do not have an extension.

<Files
    onChange={handleChange}
    onError={handleError}
    accepts={['application/dicom']}
    maxFileSize={100_000_000}
    clickable>
        Drop files here or click to upload
</Files>

I tried several combinations of accepts, including '*/*', '', '.*', '*.*', and '*', but none of them worked. Is there something that can be done to work around this? Or are changes to the library necessary to support this?

Error on build

Hi,

i'm getting this error when i'm trying to build.


 <Files
        className="files-drop-zone"
        onChange={onChange}
        onError={err => {
          // eslint-disable-next-line no-console
          console.log('onError', err);
        }}
        accepts={['image/png', 'image/jpeg', '.pdf', '.csv', 'application/*']}
        multiple
        maxFiles={3}
        maxFileSize={1000000}
        minFileSize={0}
        clickable
      >
        <div className="drop-zone">
          <div className="browse-row">
            <SmallBodyFont color="#707070">Drop files here to upload or </SmallBodyFont>
            <Button variant="outlined" className="browse-btn">
              <MicroBodyFont color="#009AD9">Browse</MicroBodyFont>
            </Button>
          </div>
        </div>

        {files.length > 0 && (
          <>
            <Divider className="divider" />
            <div className="file-list">
              {files.map(file => (
                <FileItem key={file.id} file={file} />
              ))}
            </div>
          </>
        )}
      </Files>

**There are multiple modules with names that only differ in casing.
This can lead to unexpected behavior when compiling on a filesystem with other case-semantic.
Use equal casing. Compare these module identifiers:

  • project/node_modules/babel-loader/lib/index.js?{"extends":"/project/.babelrc"}!/project/node_modules/React/index.js
    Used by 1 module(s), i. e.
    /project/node_modules/babel-loader/lib/index.js?{"extends":"/project/.babelrc"}!/project/node_modules/react-files/dist/index.js**

the error goes away when i remove the imports related to react-files.

My project uses web pack to build

Can someone help?

React 18

Hi, when this package may be available for react 18 ?

Regards

onChange is called even when there are errors

As the title says, even when there are errors, the method onChange is called. I've found 2 scenarios that can trigger this:

Scenario 1:

  • Set the accepts prop to something like: ['image/jpg', 'image/jpeg', 'image/png']
  • Select a PDF from the select files dialog

In my case, I can change the type filter in the dialog box to "All file types (*)". With this option, PDFs are visible and I can select them. After selecting a PDF or another file that it is not in the accepts prop, the onError method is called as the onChange method is called with an empty array.

This can be sorted checking that the array has elements.

Scenario 2:

  • Set the accepts prop to something like: ['image/jpg', 'image/jpeg', 'image/png']
  • Set the multiple prop to true
  • Select more than one file where one of those has an invalid extension

Again, the type filter in the select files dialog box can be changed to "All file types (*)". In this case, the onError method is called with the first file that is invalid, the onChange method is called with the files that were processed before the invalid file was encountered. Files that come after the invalid one are not processed.

Where is the issue
It is in the handleDrop method inside the index.js file. Changes to be made to this file depend on how errors are going to be handled:

  • You can stop when the first error is found and do not call onChange.
  • You can call onError for every invalid file or send an array of errors, and call onChange if there is any valid file.

In any case, calling onChange with an empty array can be misleading for the users of the library.

Can I remove an already selected file?

I want to enable the functionality of removing a file once it's already been uploaded via the user. So, in the case that the user accidentally selects a file, they can remove said file. Is this supported with this library?

Thanks in advance!

Dragging detection breaks if content is not text

Hello,
I detected this situation when I added a simple icon component to the "drop here" default text inside the <Files></Files> tag. When hovering while dragging a file over anything that's not text (i.e. the icon in this case), the active class will be removed and will never come back unless the drag zone is left and then coming back inside.

use `prop-types` lib instead of React.PropTypes

this is a great little lib, thanks for putting this together!! :D

I'm getting a deprecation warning when using react-files, sinceReact.PropTypes is being deprecated for React v16. Any plans to update this and use the prop-types lib instead?

fileAdded handler, possibility to add/replace/remove files

To make this useable in more cases I suggest adding a handler which is called, when files are added to the dropzone. Also it would be cool, to have an api to add files / remove files from the dropzone programatically.

Keep up the good work!

Need to accept any kind of file

I would like to know what should we pass in the accepts prop to accept all file types. if we pass '.' it is not showing mp4 files in onFilesChange() event. tried '.*' also but no luck.

Usability with Redux Forms

Hi,

I am playing with react-files and noticed it doesn't play well with field arrays (redux-forms). The reason is the usage of your inner files state. I am adding files to several entries in a collection of documents with redux forms and I only instantiate react-files once. The state is kept the same in react-files while I am expecting to handle my own state in my field array. That means I have to filter through all incoming files onChange and I have to think about remove and removeAll twice (remove for field array and remove for react-files state).

My question, is there a way for react-files to leave the state handling to the parent component instead of the react-files component? I was going through the src and noticed you are using state quite a bit.

Thanks for your repo!

How to read a .json file

This is most likely a newbie question, but how do I read the content of the file that I load?

Would like to load a .json file and assign it to a variable or dump it into state. This is my current (not working) code prototype:

import React, { Component } from 'react'
import Files from 'react-files'

class LoadFile extends Component {
  render() {
    return (
      <div className="files">
        <Files
          className="files-dropzone"
          onChange={file => {
            console.log(JSON.stringify(file))
          }}
          onError={err => console.log(err)}
          accepts={['.json']}
          multiple
          maxFiles={3}
          maxFileSize={10000000}
          minFileSize={0}
          clickable
        >
          Drop files here or click to upload
        </Files>
      </div>
    )
  }
}

export default LoadFile

visual preset

How can I use your visual presets? In your demo I saw very handsome file uploader, but after downloading npm packages I got lib without any visual.

Tested with Electron on Windows10 ?

I developed a prototype Electron app on Linux that uses 'react-files' to load text/csv files.

Testing the same app on Windows 10, I find that 'react-files' sees no mime type from chosen files. If I do not specify 'accepts' the chosen files are loaded. If I do specify 'accepts' no files are loaded.

If I break at https://github.com/mother/react-files/blob/master/src/index.js#L28 , then Chrome debugger shows ...

FileList {0: File, length: 1}
 - length:1
 v 0: File
     - lastModified:1515092677223
     v lastModifiedDate:Thu Jan 04 2018 14:04:37 GMT-0500 (Eastern Standard Time)
     - name: "Export20180104.csv"
     - path: "C:\Users\You\AppData\Roaming\sri\Export20180104.csv"
     - size: 8419
     - type: ""
     - webkitRelativePath: ""
     v __proto__: File
  v __proto__: FileList

I do not know where to look for a root cause for this, nor who to ask for help. Would it be a defect in react-files or webkit or electron or npm on windows?

No upload capability?

Great project and super easy to use, only there seems to be no way to upload the file data in a post to a server? This makes it nice for a simple demo but useless for anything remotely more complicated. Could potentially benefit from an included FileReader in the upload functions?

Install error

Hi, I am getting an error when I cloned the repo and did an npm install at source i.e. 'npm install'. This is the error that I am getting. Will appreciate any advice or help, thanks! Ed

npm WARN deprecated [email protected]: This version of react-dom/server contains a minor vulnerability. Please update react-dom to 16.2.1 or 16.4.2+. Learn more: https://fb.me/cve-2018-6341 npm WARN deprecated [email protected]: core-js@<3 is no longer maintained and not recommended for usage due to the number of issues. Please, upgrade your dependencies to the actual version of core-js@3. npm WARN deprecated [email protected]: CircularJSON is in maintenance only, flatted is its successor. npm WARN deprecated [email protected]: request has been deprecated, see https://github.com/request/request/issues/3142 npm WARN deprecated [email protected]: Switch to the bfj` package for fixes and new features!
npm WARN deprecated [email protected]: Package no longer supported. Contact [email protected] for more info.
npm WARN deprecated [email protected]: ๐Ÿ™Œ Thanks for using Babel: we recommend using babel-preset-env now: please read https://babeljs.io/env to update!
npm ERR! Linux 5.3.0-40-generic
npm ERR! argv "/usr/bin/node" "/usr/bin/npm" "install"
npm ERR! node v8.10.0
npm ERR! npm v3.5.2
npm ERR! code EMISSINGARG

npm ERR! typeerror Error: Missing required argument #1
npm ERR! typeerror at andLogAndFinish (/usr/share/npm/lib/fetch-package-metadata.js:31:3)
npm ERR! typeerror at fetchPackageMetadata (/usr/share/npm/lib/fetch-package-metadata.js:51:22)
npm ERR! typeerror at resolveWithNewModule (/usr/share/npm/lib/install/deps.js:456:12)
npm ERR! typeerror at /usr/share/npm/lib/install/deps.js:457:7
npm ERR! typeerror at /usr/share/npm/node_modules/iferr/index.js:13:50
npm ERR! typeerror at /usr/share/npm/lib/fetch-package-metadata.js:37:12
npm ERR! typeerror at addRequestedAndFinish (/usr/share/npm/lib/fetch-package-metadata.js:82:5)
npm ERR! typeerror at returnAndAddMetadata (/usr/share/npm/lib/fetch-package-metadata.js:117:7)
npm ERR! typeerror at pickVersionFromRegistryDocument (/usr/share/npm/lib/fetch-package-metadata.js:134:20)
npm ERR! typeerror at /usr/share/npm/node_modules/iferr/index.js:13:50
npm ERR! typeerror This is an error with npm itself. Please report this error at:
npm ERR! typeerror http://github.com/npm/npm/issues

npm ERR! Please include the following file with any support request:
npm ERR! /home/ed/Work/Sentiar/react-files/npm-debug.log
`

extension in uppercase

Hi, i would like to be able to accept uppercased extensions, does it make sense to you? would it be possible to include this in the fileTypeAcceptable?

How to reset the file for onChange to work if same file is uploaded again

HI,

Onchange function is not triggering if I tried to upload same file again, See below code as an example

   <Files
    className='files-dropzone'
    onChange={(files)=>{
          console.log(files);// This is not logging if I upload same file again
    }}
    onError={(er,file)=>{

    }}
    accepts={['image/*']}
    multiple={false}
    maxFiles={1}
    maxFileSize={10000000}
    minFileSize={0}
    clickable
    >
    Drop files here or click to upload
  </Files>

Also Multiple= false not working

Thanks in advance

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.