Created
January 11, 2018 02:18
-
-
Save kekby/f6d5b675336fddc6bc2c9209a5008616 to your computer and use it in GitHub Desktop.
react-dropzone with redux-form
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { Component, PropTypes, } from 'react'; | |
import { reduxForm, Field } from 'redux-form'; | |
import Dropzone from 'react-dropzone'; | |
const FILE_FIELD_NAME = 'files'; | |
const renderDropzoneInput = (field) => { | |
const files = field.input.value; | |
return ( | |
<div> | |
<Dropzone | |
name={field.name} | |
onDrop={( filesToUpload, e ) => field.input.onChange(filesToUpload)} | |
> | |
<div>Try dropping some files here, or click to select files to upload.</div> | |
</Dropzone> | |
{field.meta.touched && | |
field.meta.error && | |
<span className="error">{field.meta.error}</span>} | |
{files && Array.isArray(files) && ( | |
<ul> | |
{ files.map((file, i) => <li key={i}>{file.name}</li>) } | |
</ul> | |
)} | |
</div> | |
); | |
} | |
class App extends Component { | |
static propTypes = { | |
handleSubmit: PropTypes.func.isRequired, | |
reset: PropTypes.func.isRequired, | |
}; | |
onSubmit(data) { | |
var body = new FormData(); | |
Object.keys(data).forEach(( key ) => { | |
body.append(key, data[ key ]); | |
}); | |
console.info('POST', body, data); | |
console.info('This is expected to fail:'); | |
fetch(`http://example.com/send/`, { | |
method: 'POST', | |
body: body, | |
}) | |
.then(res => res.json()) | |
.then(res => console.log(res)) | |
.catch(err => console.error(err)); | |
} | |
render() { | |
const { | |
handleSubmit, | |
reset, | |
} = this.props; | |
return ( | |
<form onSubmit={handleSubmit(this.onSubmit.bind(this))}> | |
<div> | |
<label htmlFor={FILE_FIELD_NAME}>Files</label> | |
<Field | |
name={FILE_FIELD_NAME} | |
component={renderDropzoneInput} | |
/> | |
</div> | |
<div> | |
<button type="submit"> | |
Submit | |
</button> | |
<button onClick={reset}> | |
Clear Values | |
</button> | |
</div> | |
</form> | |
); | |
} | |
} | |
export default reduxForm({ | |
form: 'simple', | |
})(App); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment