Giter Club home page Giter Club logo

react-dropzone-component's Introduction

Dropzone.js Component for React

Build Status Dependency Status npm version Downloads

⚠️ Maintainers wanted! I haven't been able to keep this component up to date and would gladly hand the keys over to someone who is.

A Dropzone component for ReactJS, allowing users to "drag and drop" files into an upload area. The component uses the battle-tested Dropzone.js to provide a cross-browser-compatible upload component.

You can see a demo of the uploader with minimal configuration here.

Screen GIF

Usage

The component is initialized with a configuration object. Optional are a list of event handlers and a configuration object for dropzone.js.

If you are using one of the many module solutions, you can simply install and require this component like shown below. The package's main entry point is lib/dropzone.js, which gives you all the dropzone components. If you're rolling with ES6/ES2015, feel free to use src/dropzone.js. If you don't want any trouble at all, just add dist/dropzone.min.js as a script to your app and use <DropzoneComponent />.

⚠️ Ensure that React and ReactDOM are global variables, so that they can be reached on window.React or global.React. Many fancy boilerplates are overly fancy and somehow remove those variables.

If you are using a fancy boilerplate, you might want to require the lib directly, by using import DropzoneComponent from 'react-dropzone-component/lib/react-dropzone' or require('react-dropzone-component/lib/react-dropzone').

Please ensure that you also include two required CSS files: node_modules/react-dropzone-component/styles/filepicker.css and node_modules/dropzone/dist/min/dropzone.min.css. There are currently a bunch of good ways to combine and process CSS in React, so I'll leave it to you to choose whatever method is best for you - the component does not automatically load CSS.

To use this component without React-DOM, use version ^0.6 - from 0.7 on, we need it.

npm install react-dropzone-component
import React from 'react';
import ReactDOM from 'react-dom';
import DropzoneComponent from 'react-dropzone-component';

var componentConfig = {
    iconFiletypes: ['.jpg', '.png', '.gif'],
    showFiletypeIcon: true,
    postUrl: '/uploadHandler'
};

ReactDOM.render(
    <DropzoneComponent config={componentConfig}
                       eventHandlers={eventHandlers}
                       djsConfig={djsConfig} />,
    document.getElementById('content')
);

The configuration allows you to disable the display of CSS file type icons and to set the URL to which uploads should be posted.

Accessing the Dropzone Object

There are a bunch of operations that might require accessing the dropzone object, especially when wanting to call dropzone methods.

To get said object, use the init event, whose callback will receive a reference to the dropzone object as a parameter.

var myDropzone;

function initCallback (dropzone) {
    myDropzone = dropzone;
}

function removeFile () {
    if (myDropzone) {
        myDropzone.removeFile();
    }
}
Usage Without Automatic Posting

If you want to use this component without posting automatically to a URL but instead do the posting yourself, then you can just fill the postUrl option with a meaningless string and handle the displaying of progress by yourself using the provided event handlers. To see this in action, check out the examples!

var componentConfig = { postUrl: 'no-url' };
var djsConfig = { autoProcessQueue: false }
var eventHandlers = { addedfile: (file) => console.log(file) }

ReactDOM.render(
    <DropzoneComponent config={componentConfig}
                       eventHandlers={eventHandlers}
                       djsConfig={djsConfig} />,
    document.getElementById('content')
);
Custom Preview Template

The djsconfig property is compatible with all of the options in the official DropzoneJS documentation. Updating the preview template can be done as follows:

var ReactDOMServer = require('react-dom/server');

var djsConfig = {
  previewTemplate: ReactDOMServer.renderToStaticMarkup(
    <div className="dz-preview dz-file-preview">
      <div className="dz-details">
        <div className="dz-filename"><span data-dz-name="true"></span></div>
        <img data-dz-thumbnail="true" />
      </div>
      <div className="dz-progress"><span className="dz-upload" data-dz-uploadprogress="true"></span></div>
      <div className="dz-success-mark"><span></span></div>
      <div className="dz-error-mark"><span></span></div>
      <div className="dz-error-message"><span data-dz-errormessage="true"></span></div>
    </div>
  )
}
Custom Post Parameters

To add custom parameters to your request, add a params property to your Dropzone.js configuration object.

var djsConfig = {
    addRemoveLinks: true,
    params: {
        myParameter: "I'm a parameter!"
    }
};

var componentConfig = {
    postUrl: '/uploadHandler'
};

ReactDOM.render(<DropzoneComponent config={componentConfig} djsConfig={djsConfig} />, document.getElementById('content'));

Custom Dropzone Area

In case you need to customize the dropzone area, you may pass a jQuery compatible selector in the config object.

var componentConfig = {
    postUrl: '/uploadHandler',
    dropzoneSelector: 'body',
};

ReactDOM.render(
  <DropzoneComponent config={componentConfig} />,
  document.getElementById('content'),
);

The code above will use the entire page body as the dropzone area.

Callbacks

Callbacks can be provided in an object literal.

var eventHandlers = {
    // This one receives the dropzone object as the first parameter
    // and can be used to additional work with the dropzone.js
    // object
    init: null,
    // All of these receive the event as first parameter:
    drop: callbackArray,
    dragstart: null,
    dragend: null,
    dragenter: null,
    dragover: null,
    dragleave: null,
    // All of these receive the file as first parameter:
    addedfile: simpleCallBack,
    removedfile: null,
    thumbnail: null,
    error: null,
    processing: null,
    uploadprogress: null,
    sending: null,
    success: null,
    complete: null,
    canceled: null,
    maxfilesreached: null,
    maxfilesexceeded: null,
    // All of these receive a list of files as first parameter
    // and are only called if the uploadMultiple option
    // in djsConfig is true:
    processingmultiple: null,
    sendingmultiple: null,
    successmultiple: null,
    completemultiple: null,
    canceledmultiple: null,
    // Special Events
    totaluploadprogress: null,
    reset: null,
    queuecomplete: null
}

To provide a single callback, simply override one of these events with your function reference. If you want to provide multiple callbacks, simply provide an array with your function references.

var callbackArray = [
    function () {
        console.log('Look Ma, I\'m a callback in an array!');
    },
    function () {
        console.log('Wooooow!');
    }
];

var simpleCallBack = function () {
    console.log('I\'m a simple callback');
};

Updating the Component's Properties

This React Component is a wrapper around Dropzone.js - meaning that Dropzone.js is not aware of the React component life cycle. When you update the component's properties, we will use a copy of jQuery's extend method (see documentation) to merge new options into the Dropzone's properties object.

If you want to fundamentally change things about your dropzone, we recommend that you either modify the Dropzone object directly or destroy and recreate the component.

Server Example

This component comes with a small server example. To try it out, simply run npm install and npm start from the example folder. Visit http://localhost:8000/example/ to see the uploads working.

To check out the (super small) source code for this simple upload-accepting server, check out example/src-server/ and example/server.js. The component works with any server infrastructure, though!

License

MIT. For details, please consult README.md.

react-dropzone-component's People

Contributors

bdefore avatar brianium avatar charleschenster avatar christaggart avatar ciceropablo avatar danielruf avatar drborges avatar erikschlegel avatar etienne-lambert avatar felixrieseberg avatar fritz-c avatar ginkcode avatar hansoksendahl avatar ko avatar lo-tp avatar myarete avatar mygoare avatar patrickomeara avatar pjeweb avatar rootulp avatar tobob avatar vfil 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-dropzone-component's Issues

using dropzone inside form

Hi Felix,

i am new to React and still figuring things out. If you could help me with this issue i have on my mind, i will grateful

I have a form for creating a new item on a queue. This item will have an avatar. So in the form i have all the fields required for the item and the dropzone component to drag and drop images of the item.

the thing is that I want to post everything together to the server, how could i do this? because i saw that if i wanted to do the post myself i had to remove the 'postUrl' property but then i had to add the 'action' prop to the component. So i am a bit confused

Thanks you

React peer dependency

I'm currently using React 0.14.0-beta1 and thus I can't satisfy your peerDependencies requirements.
In fact I get the following error:

The package react does not satisfy its siblings' peerDependencies requirements!
Peer [email protected] wants react@^0.13.0

I hope there is a conventional way for these two to work together?

@felixrieseberg your help is appreciated 🙏

Error: Cannot find module 'browserify-shim'

I got the following error from my gulp script:

[18:38:43] gulp-notify: [Compile Error] Cannot find module 'browserify-shim' from '/path/to/my/project/node_modules/react-dropzone-component'

I'm using browserify for my build, but I don't have browserify-shim installed. I suppose I could fix it by installing browserify-shim manually, but that doesn't quite seem to jive with the npm mindset.

I'm using v0.9.0, and I'm assuming this came about from the changes made around here

Integrating this with Rails and Browserify

I use this code snippet to get started (in dropzone.js.coffee):

dropZone = require('react-dropzone-component')
@DropzoneComponent = React.createClass
  render: ->
    React.createElement dropZone

(in render html.haml):

= react_component 'DropzoneComponent'

I just want to test if I installed React-Dropzone-Component correctly, however, it keeps throwing this error:

BrowserifyRails::BrowserifyError
events.js:85
      throw er; // Unhandled 'error' event

Please help.

Server-side rendering with .NET

I've tried to render the component on the server but it doesn't work properly, because it requires the window object.

contentLoaded(window, Dropzone._autoDiscoverFunction);

The quoted line is causing the issue. I tried faking an empty window object but then it attempts to use other browser dom specific constructs. Is possible to attach the dom specific handlers only when the window object is present or is there any other workaround?

Error with previewTemplate option after updating dropzone

I'm having this error after updating all of my stack to react 0.14 which in case of dropzone it's somehow related to options I'm not using at all.

Uncaught TypeError: Cannot read property 'trim' of undefined

error is related to this line (not my code) :

file.previewElement = Dropzone.createElement(this.options.previewTemplate.trim());

Here is my code and as you can see I don't have previewTemplate as an option:

renderImageUpload() {
        let componentConfig = {
            allowedFiletypes: ['.jpg', '.png'],
            postUrl: '/image_upload'
        };
        var eventHandlers = {
            removedfile: this.onImageRemoved,
            success: this.onImageUploaded
        };
        let djsConfig = {
            paramName: "image"
        };
        return <DropzoneComponent config={componentConfig} 
                       eventHandlers={eventHandlers} 
                       djsConfig={djsConfig} />;
    },

I do appreciate any kind of help. Thanks.

Leaving postUrl blank throws error

Firstly, thanks for this, very useful. Though I've run into the following problem.

I'm using Parse so I'd like to handle the file upload myself rather than go through postUrl.

As suggested:

Usage Without Automatic Posting

If you want to use this component without posting automatically to a URL but instead do the posting yourself, then you can just leave the postUrl option empty and handle the displaying of progress by yourself using the provided event handlers.

Though when I leave postUrl I recieve the following error:

Uncaught Error: No URL provided.

Any thoughts how I can work around this?

Passing extra parameters

Hi,

Can you describe where and how to pass some extra parameters? I tried the different methods proposed on SO or other sites for a standard dropzone usage and none of them seem to work with the component.

Thanks

removedfile handler triggered when componentWillUnmount

Hi,

I'm using the removedfile handler to delete files on the server with an ajax call, works great!

However, on the client side once the form is submitted (ajax) and successful, we transition (react-router) to another page. At this stage (componentWillUnmount), the removedfile handler is triggered automatically which obviously deletes the files server side...

I checked your source code and found out that when the component will unmount, the dropzone object is destroyed. Commenting out this line avoids to have the removedfile handler triggered but may be could induced some side effect.

componentWillUnmount: function () {
    //  this.dropzone.destroy();
},

If this is a normal behaviour how to avoid triggering removedfile when unmounting the component?

online demo please :)?

Hi- If it's feasible, would love an online demo of this to add to react.rocks. Thanks!

Example project is broken

I'm trying to run the project on my local machine but the example project seems misconfigured. The route /example doesn't exist. As a minor detail, the link in index.html points to port 8000,

regards - Emil

Provide clean compiled build without jsx and es6 code

Requiring node modules shouldn't depend on es6 and jsx transpilers at all. For example here is the part of my webpack config, I am skipping node_modules to make build faster (commonly used practice):

module: {
    loaders: [{
      test: /\.(js|jsx)?$/,
      loaders: ['react-hot', 'babel?stage=0'],
      exclude: /node_modules/
    }]
  }

How to restrict multiple upload

Hi,
Thanks for making a good plugin like this, I want to restrict multiple uploads from the drop zone,
How can i do it ? I have seen uploadMultiple option in your file , but how to use ?

I have tried the following, in the example_default.js file

var componentConfig = {
allowedFiletypes: ['.jpg', '.png', '.gif'],
showFiletypeIcon: true,
uploadMultiple: false,
maxFiles: 1,
postUrl: '/uploadHandler'
};

But, It is not working, please help me.

React is undefined

hi there,

I'm having problems trying to run this component.
I've installed the package using npm.
Then I'm trying to 'require' it as follows - var DropzoneComponent = require('react-dropzone-component');
However, i then get an exception in icon.js - on this line: var React = (typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null);

React doesn't exist on the window object, so it's undefined.

The same is also true when clone the repo, run npm install, then gulp and open my browser here - http://localhost:8000/example/

It's trying to find React on the global object.

Can you anyone help?
thanks

Preview template as React component

Is it possible to have the preview template as a React component?

   var ImagePreview = React.createClass({
        deleteImage: function () {
            // delete the image
        },

        render: function () {
            return <img src={this.props.imageUrl} onClick={this.deleteImage} />
        }
    });

    // and in the actual component using the <DropzoneComponent />
    ...
    var djsConfig = {
        previewTemplate: ImagePreview
    };

other than that, this is so far the best image uploader for React I've found!

Drag and Drop from Body HTML

Hi Felix,
where the setting how to upload drang and drop from body? form example from Dropzone

new Dropzone(document.body, { // Make the whole body a dropzone
    url: "/upload/url", // Set the url
    previewsContainer: "#previews", // Define the container to display the previews
    clickable: "#clickable" // Define the element that should be used as click trigger to select files.
  });

Issue with react 0.14.2

React.renderToStaticMarkup is deprecated. Please use ReactDOMServer.renderToStaticMarkup from require('react-dom/server') instead.

How about require depends css into js

We are planing to use this component in our project but meet a difficult. That is how to package the required css file into final bundle. Because this css is not required in js of this component so we have to require it by ourself. Can it require depends stuffs by itself ? Any update in progress about this?

Flux example

Hi,

It would be really helpful to provide a simple Flux example where the user drops the files, then clicks upload to send them to the server. How hard is it to accomplish this? I'd be willing to help on that if you give me some pointers. Like how do I call processQueue() given that I don't have access to that method directly from your component.

Thanks,

minimaximus

Dynamically pass djsConfig params based on parent's props.

Hey, thanks for the component. I'm trying to dynamically set the djsConfig params based on the parent's props, like so:

var Table = React.createClass({
    render() {
        var that = this;
        var dropzoneConfig = {...};
        var eventHandlers = {...};

        var djsConfig = {
            uploadMultiple: true,
            maxFilesize: 11,
            params: {
                id: that.props.id,
                name: that.props.name
            }
        };

        return(
            <Dropzone djsConfig={djsConfig}
                      eventHandlers={eventHandlers}
                      dropzoneConfig={dropzoneConfig}/>
        );

    }
});

From what I understand the problem is that because dropzone gets initialized only on componentDidMount the props won't be passed down on the parent component's first re-render for some reason.

To explain further, say I have Table A and Table B in a list view, both clickable and they go to their single table view (with react router). I click on Table A for the first time, everything works as expected. Go back to the list, click on Table B, the djsConfig object still has Table A’s id and name props. If I go back and load Table B again only then are the correct props set.

Is there any workaround for this?

For the time I hacked around the source and added

        componentWillReceiveProps: function() {
            this.dropzone.destroy();
            this.componentDidMount();
        },

which is really bad. I'd appreciate any input.

NPM Version doesn't have latest commit.

I have done

npm i react-dropzone-component

And when I view

/lib/dropzone.js

The commit that resolves the Key warning doesn't exist. The line still shows

icons.push(React.createElement(IconComponent, {filetype: this.props.config.allowedFiletypes[i]}));

Disable Preview

Can we disable preview image upload progress ? or can move the preview image upload progress to another component?

Example does not work

I tried example, but get error
Warning: React.createElement: type should not be null, undefined, boolean, or number. It should be a string (for DOM elements) or a ReactClass (for composite components).
Uncaught Invariant Violation: _registerComponent(...): Target container is not a DOM element.
My jsx-file:

var DropzoneComponent = DropzoneComponent;
var eventHandlers = {
    // This one receives the dropzone object as the first parameter
    // and can be used to additional work with the dropzone.js
    // object
    init: null,
    // All of these receive the event as first parameter:
    drop: callbackArray,
    dragstart: null,
    dragend: null,
    dragenter: null,
    dragover: null,
    dragleave: null,
    // All of these receive the file as first parameter:
    addedfile: simpleCallBack,
    removedfile: null,
    thumbnail: null,
    error: null,
    processing: null,
    uploadprogress: null,
    sending: null,
    success: null,
    complete: null,
    canceled: null,
    maxfilesreached: null,
    maxfilesexceeded: null,
    // All of these receive a list of files as first parameter
    // and are only called if the uploadMultiple option
    // in djsConfig is true:
    processingmultiple: null,
    sendingmultiple: null,
    successmultiple: null,
    completemultiple: null,
    canceledmultiple: null,
    // Special Events
    totaluploadprogress: null,
    reset: null,
    queuecomplete: null
}
var componentConfig = {
    iconFiletypes: ['.jpg', '.png', '.gif'],
    showFiletypeIcon: true,
    postUrl: '/uploadHandler'
};

var callbackArray = [
    function () {
        console.log('Look Ma, I\'m a callback in an array!');
    },
    function () {
        console.log('Wooooow!');
    }
];

var simpleCallBack = function () {
    console.log('I\'m a simple callback');
};


var djsConfig = {
};

ReactDOM.render(
    <DropzoneComponent config={componentConfig}
                       eventHandlers={eventHandlers}
                       djsConfig={djsConfig} />,
    document.getElementById('content')
);

process is not defined

I am trying to use this component via global script, and have added it to my html as a simple script tag

<html>
    <body>
       <script src="node_modules/react/dist/react.js"></script>
       <script src="node_modules/react-dom/dist/react-dom.js"></script>
       <script src="node_modules/react-dropzone-component/dist/dropzone.js"></script>
</body></html>

However, the dropzone component is throwing an uncaught exception under ReactPerf saying 'process is not defined':

measureMethods: function (object, objectName, methodNames) {
    if (process.env.NODE_ENV !== 'production') {

Am I not able to use this component without adding a module loader and using require/define? The description implies that I should be able to add this using a script tag.

Issue due to DOM changes

Hi,
I'm getting the following error after uploading an image.
Uncaught NotFoundError: Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node.

Also i don't want to show any preview of the uploading image.

there is any workaround for this ?

Thanks
SIjo

Reason: CORS preflight channel failed

I have used Dropzone component in one of my component for upload the CSV.

as a postUrl I am passing my webservice url, domain is different
I mean my site working on http://localhost:50130/Importcsv and I have given the URL http://localhost:8005//UploadFile

-I have checked with RestClient my Service is working fine but when I tried to give the same URL it gives me error 404(Not Foun) with following error in browser console

Cross- Origin application blocked : the Same Origin Policy is reading from the external source at http: // localhost: 8005 // Upload File TenantId = bc984c79 - d4f9-4dd6 - b8ad - f723aa2ba4af ​​& format = json not matter ? . ( Reason: CORS preflight channel failed ) .

add params to headers

amazing work!

my backend is based on JWT (json web token) , it's there a way to add 'Authorization' key in request header ?

Strange cross origin setup

Please remove the Access-Control-Allow-XXX headers from being set on the client. These headers are meant to be returned by the server, not sent by the client. The trouble here is that in cross-origin setup on the server you must explicitly specify the allowed headers, therefore with the default setup you would have to allow Access-Control-Allow headers on the server, which seems a bit strange.

Please also consider setting withCredentials default back to false, as it is in dropzone. Not everybody uses cross-domain authentication, but even if somebody uses it, it's not always cookies.
The problem with a default setup like this is that if you use withCredentials: true, then on the server side you must explicitly whitelist all allowed domains instead of saying Allow-Origin=*.

Docs should mention style dependencies

It would be helpful to mention that you'll need to import styles/filepicker.css as well as node_modules/dropzone/dist/min/dropzone.min.css in order for the component to lay out correctly.

Hook Redux actions to the component.

Hi,
it would be great to have a way to integrate this component with the redux architecture.

One of the reasons is to have a better management of the upload endpoint.
In standard react-redux there are additional header being added to the request (authentication mainly).

I'm thinking to leverage the eventHandlers hook but I'm not sure how the component will behave without a componentConfig.postUrl set.
Also, would be useful to feed back the information to the component (for instance the uploadProgress).

Thoughts?

Anyone tried this with rails ?

I'm using react for my rails project. File uploads in powered by carrierwave gem. Anyone tried this component with same stack ?

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.