Giter Site home page Giter Site logo

karimmokhtar / react-drag-drop-files Goto Github PK

View Code? Open in Web Editor NEW
241.0 3.0 86.0 1.34 MB

Light and simple Reactjs drag and drop files library to use with very flexible options to change, so you put whatever the design you want for your drop-area. Users can drag and drop or even select the file anywhere in the window.

License: MIT License

JavaScript 15.12% TypeScript 73.21% HTML 9.19% CSS 2.47%
react drag-and-drop drag drop styled-components file file-upload react-drag-and-drop react-draggable react-drag-and-drop-files

react-drag-drop-files's Introduction

React Drag and Drop Files

Version code style: prettier npm download

Light and simple reactjs drag and drop files library to use with very flexible options to change, so you put whatever the design you want for your drop-area. Users can drag and drop or even select the file anywhere in the window.

Demo

Edit react-drag-drop-files

Installation

Install it from npm (using NPM).

npm i --save react-drag-drop-files

or:

yarn add react-drag-drop-files

Usage

Using react hooks just as simple as:

import React, { useState } from "react";
import { FileUploader } from "react-drag-drop-files";

const fileTypes = ["JPG", "PNG", "GIF"];

function DragDrop() {
  const [file, setFile] = useState(null);
  const handleChange = (file) => {
    setFile(file);
  };
  return (
    <FileUploader handleChange={handleChange} name="file" types={fileTypes} />
  );
}

export default DragDrop;

Options

Option Type Description value example
name string the name for your form (if exist) "myFile"
multiple boolean a boolean to determine whether the multiple files is enabled or not true OR false - false by default
label string the label (text) for your form (if exist) inside the uploading box - first word underlined "Upload or drop a file right here"
required boolean Conditionally set the input field as required true or false
disabled boolean this for disabled the input true OR false
hoverTitle string text appears(hover) when trying to drop a file "Drop here"
fileOrFiles Array or File or null this mainly made because if you would like to remove uploaded file(s) pass null or pass another file as initial
classes string string with the classes wished to add "drop_area drop_zone"
types Array array of strings with extensions to check and go throw ['png', 'jpeg', ...]
onTypeError function function that will be called only of error occurred related to type (err) => console.log(err)
children JSX Element, any if you want to replace the current design inside the box of drop zone. (it will remove the default exist style) <div><p>this is inside drop area</p></div> or just text
maxSize number the maximum size of the file (number in mb) 2
minSize number the minimum size of the file (number in mb) 1
onSizeError function function that will be called only if error related to min or max size occurred (file) => console.log(file)
onDrop function function that will be called when the user drops file(s) on the drop area only (file) => console.log(file)
onSelect function function that will be called when the user selects file(s) on click the file area only (file) => console.log(file)
handleChange function function that will be called when the user selects or drops file(s) (file) => console.log(file)
onDraggingStateChange function function that will be called with the state of dragging (dragging) => console.log(dragging)
dropMessageStyle CSS Properties A CSS property to style the hover message {backgroundColor: 'red'}

How to contribute:

  • Please follow the instructions inside this file: here

Upcoming...

  • Contribution Guide
  • Github actions

License

MIT

react-drag-drop-files's People

Contributors

anadoly avatar anti-duhring avatar aprilmintacpineda avatar dante01yoon avatar iamdipanshusingh avatar jirihofman avatar karimmokhtar avatar lukeflima avatar mykybo avatar room9design avatar saitharunsai avatar thebedroomprogrammer avatar troywolf avatar tvox15 avatar vj-27 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-drag-drop-files's Issues

Not able to access Input with passing ref

In the project I require to control the input element e.g. to trigger input file event with some button outside the FileUploader component.
But by passing ref to FileUploader component it doesn't do anything. I think it do not take any prop as ref. So it might be good if we can pass ref to get more control over the input element inside FileUploader component.

If it is there already can anybody please explain how to use that. Thanks

Possible to disable click to select?

I have recently started using this project, but I ran into a feature limitation.

I was wondering if it is possible to make the FileUploader only be drag and drop? I am using it to overlay a table, so it would be preferred if it does not open the select file dialog when clicking a cell.

Adding aria tags

Hi,

I don't see any way to add aria tags to the <input/> element.

I need to add tags like:
aria-required
aria-describedby
aria-invalid

Is there a workaround?

Or should I make a PR for it?

How to reinitialize Fileuploader component?

Hi,

I am facing an issue when I tried to upload same image two time, Could you please let me know if there is a reinitilization of exist here, My code is given below

<div className="imagedragdrop">
<FileUploader 
    classes={"draggableInput"}
    onSelect={ async (file)=>{
        console.log(file)
    }}
    handleChange={ async (file)=>{
        console.log(file); // This is not working if same image is upload multiple times
    }} 
    name="testImg" 
    types={imgTypes} 
/> 
</div>

Thanks in advance

Add multiple files

Very good package which lacks only one feature, that is multiple file selection.

Missing dependency

Hi, I just stumbled upon this and tried it. I got an error about missing dependency:

.yarn/unplugged/styled-components-virtual-9691129a54/node_modules/styled-components/dist/styled-components.browser.esm.js:1:0
Module not found: styled-components tried to access react-is (a peer dependency) but it isn't provided by its ancestors; this makes the require call ambiguous and unsound.

Required package: react-is
Required by: styled-components@virtual:dde1fece8d8008abee890dec5f02170cbc3b5cdb45cbb9d1ca588b2aa4603145e4ef83b240eb2a9151decb9c17e0a486ce3a63bf43859945391f42be84a31faf#npm:5.3.5 (via /.yarn/unplugged/styled-components-virtual-9691129a54/node_modules/styled-components/dist/)

Ancestor breaking the chain: babel-plugin-styled-components@virtual:9691129a54311d74830d740c933802844a8e85eee8626ffd8747a04d20f491beb3d342fdfc48789f23db385d47e5af24cec6536671e9ebffc31889eb0fa7cdd8#npm:2.0.7
Ancestor breaking the chain: react-drag-drop-files@virtual:dc3fc578bfa5e06182a4d2be39ede0bc5b74940b1ffe0d70c26892ab140a4699787750fba175dc306292e80b4aa2c8c5f68c2a821e69b2c37e360c0dff36ff66#npm:2.3.7

This is next.js project and is using yarn package manager with pnp.
yarn version: 3.2.1
node version: 17.9.1
next.js: 12.1.6

Installing dependency works.
Cheers

Restart component original state

I'd like to, if I empty any set of files that have been dropped, the component message to restart to the original (i.e. from "Uploaded successfully. Upload another?" back to "Upload or drop a file right here")

How could I achieve this?

Need method to disable `hoverTitle`

Version: 2.3.2

By default, when user drags file over drop zone, "Drop here" text appears. This is controlled with the hoverTitle property. For our use case, we want to disable this hover text completely. However, the hoverTitle does not seem to provide a way to disable this completely. Setting a blank string (''), null, or false all result in the default "Drop here" text showing. I can set to a single space hoverTitle=' ', but this still results in a gray dot showing upon hover.

Thanks @KarimMokhtar, for creating and sharing your work!

How to style the component?

I wish to change the border color and border-radius of the component but was not able to. When I add a new className to classes, your class .iciELI takes precedence over any class I wish to write to add extra CSS.

How to access and change internal state of files.

Problem: When I upload three files and remove them one by one, by setting the files[i]=null. Then if I again upload the same files it doesn't trigger the handleChange function. I assume that since the internal state of files still has the same names of the files thus it is not changing the state of these files.

Does it support audio file(mp3)?

I am trying to upload an mp3 file, but it doesn't work. I tried with the image files and it works great, but not the mp3 files.

How to preview image upload

It works great for me but i don't know how to get the preview image, can you help me ? thanks you so much

NoModificationAllowedError

No problems in Chrome. When I DnD a file in Firefox, my React app blows up with:

NoModificationAllowedError: Modifications are not allowed for this document

Per https://developer.mozilla.org/en-US/docs/Web/API/DataTransfer/clearData

Note: This method can only be used in the handler for the [dragstart](https://developer.mozilla.org/en-US/docs/Web/API/Document/dragstart_event) event, because that's the only time the drag operation's data store is writeable.

It looks like this code is doing clearData() in the drop handler:
https://github.com/KarimMokhtar/react-drag-drop-files/blob/dev/src/useDragging.tsx#L56

This Stack Overflow is related:
https://stackoverflow.com/questions/58201273/nomodificationallowederror-in-firefox-when-using-dnd-events

File reload not working

Hello, thank you for your job! I have a problem in Google Chrome when I try to reload the same file another time. If I upload a file, then change the state to null, and try to upload the same file again, the onChange or onSelect event doesn't fire. Prop value fileOrFiles={state} doesn't work

First two uploaded images take long time

Hi, I noticed the first two images take a long time to upload, about 7/8 seconds each. I've seen the same problem happen in the demo on codesandbox as well.
There is something wrong on my side or it's a known bug?
Thansk

support for react native

Your package is what i need to use for my react native project, but when i add the package and try to run my app through it, it gives me this error, I tried reinstalling and clearing my cache but that didn't help.
I am using react-native => 0.60, is there any requirement of the latest version for it?

Screenshot 2022-05-31 at 4 03 51 PM

Dependency Problem with React 18.0

Hi, I just tried to play around with this package but was met with a dependency error on install. I'm using React 18 and react-drag-drop-files is on 17.0.2. I'm guessing bumping the version would fix this.

Shell output:

react$ npx create-react-app
....
react$ cd test1/
test1$ npm i react-drag-drop-files
npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR! 
npm ERR! While resolving: [email protected]
npm ERR! Found: [email protected]
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@"^17.0.2" from [email protected]
npm ERR! node_modules/react-drag-drop-files
npm ERR!   react-drag-drop-files@"*" from the root project
npm ERR! 
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR! 
npm ERR! See /Users/marlon/.npm/eresolve-report.txt for a full report.

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/marlon/.npm/_logs/2022-03-29T16_20_10_035Z-debug-0.log

Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:

I am trying to make a small example react project that uses this npm package drag and drop file picker:
https://www.npmjs.com/package/@yelysei/react-files-drag-and-drop

I made a fresh react project with npx create-react-app my-app.

I installed the package and added the filesDragAndDrop component to my App.js file like so:

import logo from './logo.svg';
import './App.css';
import FilesDragAndDrop from '@yelysei/react-files-drag-and-drop';

function App() {
  return (
    <div >
      welcome

      <FilesDragAndDrop
        onUpload={(files) => console.log(files)}
        count={3}
        formats={['jpg', 'png', 'svg']}
        containerStyles={{
            width: '200px',
            height: '200px',
            border: '1px solid #cccccc',
        }}
        openDialogOnClick
    >
        <div style={{
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
        }}>
            Drop files here
        </div>
    </FilesDragAndDrop>


    </div>
  );
}

export default App;

When I run my react project, it starts fine with no errors. but when I visit my home page in chrome, I get a bunch of red console errors that prevent the page from loading

react.development.js:1465 Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See `https://-f-b.me/-re-act-inv-alid-hook-call` for tips about how to debug and fix this problem.
    at resolveDispatcher (react.development.js:1465:1)
    at Object.useState (react.development.js:1496:1)
    at FilesDragAndDrop (index.js:43:1)
    at renderWithHooks (react-dom.development.js:16175:1)
    at mountIndeterminateComponent (react-dom.development.js:20913:1)
    at beginWork (react-dom.development.js:22416:1)
    at HTMLUnknownElement.callCallback (react-dom.development.js:4161:1)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:4210:1)
    at invokeGuardedCallback (react-dom.development.js:4274:1)
    at beginWork$1 (react-dom.development.js:27405:1)

I tried to investigate what this error meant on the linked site:
https://reactjs.org/warnings/invalid-hook-call-warning.html

running npm ls react-dom i get this:

$ npm ls react-dom
[email protected] /mnt/c/Users/marti/Documents/projects/react-draganddrop-demo
├─┬ @yelysei/[email protected]
│ └── [email protected]
└── [email protected]

so 2 versions of react-dom, and the other command shows no results:

$ npm ls react-native
[email protected] /mnt/c/Users/marti/Documents/projects/react-draganddrop-demo
└── (empty)

and running npm ls react shows 2 react versions:

[email protected] /mnt/c/Users/marti/Documents/projects/react-draganddrop-demo
├─┬ @yelysei/[email protected]
│ └── [email protected]
└── [email protected]

is the blocking error I am facing caused by me having multiple react versions installed? or did i configure my component in App.js incorrectly?

Option to change uploaded text

Hello, great job with this. Could you please add an option to change the text "Uploaded Successfully!. Upload another?". There are options to change everything else, but not this it seems.

Style modification of Label element

Would be nice to be able to adjust default "min-width" style of the the Label element as a property of FileUploader. Or if suggestions on how to adjust any of the default styles of the Label, that would be much appreciated.

Issue with file types

I am having problem with file types. I want to accept *.lic files, and I can not get it to work... Here is my code:

import { FileUploader } from "react-drag-drop-files";

const fileTypes = ['lic'];

<FileUploader 
  label="Drop your license (*.lic) file here"
  handleChange={handleChange} 
  name="file" 
  types={fileTypes} 
/>

When I drag and drop my file DWX-J13M-DRCI-JQR1.lic the component would say error File type/size error, Hovered on types!.

What am I doing wrong?

Feature request: required prop & focus indicator

It would be great if basic required validation was added. E.g:

<FileUploader required={isRequired} />

  • add required as a prop
  • apply required prop to input field
  • change input css from display: none to display: block
  • add input css opacity: 0;
  • add input css position: absolute;
  • add input css pointer-events: none;

The CSS changes mean:

  • Native browser validation prompts display when required is set to true.
  • The dropzone can receive keyboard focus and have a visible focus indicator (for accessibility, see WCAG 2.4.7)

Multiple attribute doesn't work for me

So I like your module it's simple and easy to work with but now I have decided to try it with multiple files but it doesn't work.
My code looks like this:
<FileUploader multiple={true} ...
But it's still not able to upload multiple files. I tried also passing true argument as string but didn't work.
Is this problem on my side or anybody has this issue too? Can you please fix this? Thanx.

style drag and drop border

Hello! Any way to change default border styling? Seems like it's currently border style dotted and color blue. Thanks!

Minimum React Version

The minimum require version of React and React DOM now is 18, can you lower it to 17? is there any major update that need 18?

Dropzone size

Hi, I am new in frontend, first thanks for your library, its so handy.
I have tried to change the size of the dropzone and icon but it does not work,
maybe someone could give me a hint?
thanks!

Remove default styling if FileUploader has children

Trying to overwrite the default style. This is the result

image

Notice the border behind the white div.

<DropZone>
                <div className="bg-white rounded-md shadow-lg">
                    <div className="items-center p-4 m-4 text-center border-4 border-dotted w-96 h-96">
                        <p className="self-auto">Drag and drop (Or click to drop) a MP4 file</p>

                        <svg
                            xmlns="http://www.w3.org/2000/svg"
                            className="w-2/3 pt-8 m-auto h-2/3"
                            fill="none"
                            viewBox="0 0 24 24"
                            stroke="gray"
                        >
                            <path
                                strokeLinecap="round"
                                strokeLinejoin="round"
                                strokeWidth={2}
                                d="M5 19a2 2 0 01-2-2V7a2 2 0 012-2h4l2 2h4a2 2 0 012 2v1M5 19h14a2 2 0 002-2v-5a2 2 0 00-2-2H9a2 2 0 00-2 2v5a2 2 0 01-2 2z"
                            />
                        </svg>
                    </div>
                </div>
            </DropZone>
import { useState } from "react";
import { FileUploader } from "react-drag-drop-files";

function DropZone(props) {
  const [file, setFile] = useState(null);
  const handleChange = file => {
    setFile(file);
    console.log(file.name)
  };
  return (
    <FileUploader 
        handleChange={handleChange} 
        name="file" 
        types={props.fileTypes} 
        hoverTitle="Drop Here!"
        children={props.children}
    />
  );
}
export default DropZone;

Upload File window opens twice & disabled doesn't work in Next.js

When the package is imported and run in Next.js, the file upload window opens twice when the component is clicked. Also, the file upload is still clickable & will open a window even when disabled is set to true. I haven't been able to replicate this in regular React apps.

Change the caption "Drop Here"

It seems that the caption "Drop Here" is hardcoded in English. Is there a way to change this string?

EDIT: I think there is more than one message that is hardcoded in English. It would be great if it supports multiple languages in somehow

Reset file value

When I upload image, I don't know how I can remove the success view (Uploaded Successfully!)

image

TypeError: Cannot read properties of null (reading 'useRef')

I use the following code to get the file uploader in my next js project's components
image

But upon running the npm run dev, the error occured coming from react-drag-drop-files/dist/react-drag-drop-files.cjs.js (1:5004)

image
any idea would be appreciated!

Image re-upload is not working

When we upload an image, and then try to upload the same image again, change event is not firing. Also is it possible to make it compatible with react 17?

React Version Conflict

Your component is the perfect match with what I needed. But it doesn't support react version less than 17. I'm working on a project of react 16.3.1 version. Can you please tell me a way to make it work on this version?

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.