Search code examples
javascriptreactjsdropzone.jsredux-form

Adding a field for uploading multiple images in ver 6.0 rc.3 of redux-form


I am experimenting the redux-form v6.0.0 rc.3 and trying to add a field for uploading multiple images.

Idea 1: add a field with type="file"

attachImages(images) {
        console.info('images received: ', images);
    }

<Field
                      name="pics"
                      component={renderInput}
                      placeholder="Pictures"
                      onDrop={this.attachImages}
                      type="file" />

Idea 2: Using the third-party Dropzone component:

onDrop(files, evt) {
        console.log('received files: ', files);
        evt.preventDefault();
    }

<Dropzone
                     onDrop={ this.dropFile }
                 >
                   <div>Try dropping some files here, or click to select files to upload.</div>
                 </Dropzone>

I've tried both ideas, but the first one cannot trigger the onDrop function at all, and the second idea seems more promising, however, I don't know how to add a field with the API for ver 6.0.0 rc.3. Anyone knows?


Solution

  • After much struggling, I made my second idea work by modifying the onDrop callback for the Dropzone component a little bit. The modification includes using the dispatch function of the reduxForm wrapper component with the action type redux-form/CHANGE.

    onDrop(files, evt) {
            console.log('received files: ', files);
            evt.preventDefault();
            this.props.dispatch({
                type: 'redux-form/CHANGE',
                field: 'images',
                value: files, // files is an array of File
            });
        }
    

    Then in the reducer, I watch for the action type redux-form/CHANGE and extract the files for uploading. This may be a little bit too hacky, but it works with the current ver 6 RC3 API.