Using react-dropzone (https://www.npmjs.com/package/react-dropzone) and getting files logging to the console, but can't get image preview to populate on state change. Any idea what I'm doing wrong?
export default class JoinForm extends Component {
constructor(props) {
super(props)
this.state = {
imageFiles: []
}
}
onDrop(imageFiles) {
this.setState({
imageFiles: imageFiles
})
console.log(imageFiles)
}
render() {
return(
<form className='join-form' ref='joinForm' autoComplete='off'>
<Dropzone
onDrop={this.onDrop}
className='dropzone'
activeClassName='active-dropzone'
multiple={false}>
<div>Drag and drop or click to select a 550x550px file to upload.</div>
</Dropzone>
{this.state.imageFiles.length > 0 ? <div>
<h2>Uploading {this.state.imageFiles.length} files...</h2>
<div>{this.state.imageFiles.map((file) => <img src={file.preview} /> )}</div>
</div> : null}
</form>
)
}
};
Use URL. createObjectURL(file) on the files returned from the onDrop callback. See https://react-dropzone.js.org/#!/Previews for more info.
We can achieve this by doing a static method URL. createObjectURL(). The method URL. createObjectURL() takes an object and returns a URL representing the object used as a parameter.
js file: import Dropzone from "./Dropzone/Dropzone"; We'd add the component as a child of the div element with class name content : return ( <div> <p className="title">React Drag and Drop Image Upload</p> <div className="content"> <Dropzone /> </div> </div> );
The useDropzone hook just binds the necessary handlers to create a drag 'n' drop zone. Use the getRootProps() fn to get the props required for drag 'n' drop and use them on any element. For click and keydown behavior, use the getInputProps() fn and use the returned props on an <input> .
Correct answer to this: being a dummy and forgot to bind this.
<Dropzone
onDrop={this.onDrop.bind(this)} //<= Here
className='dropzone'
activeClassName='active-dropzone'
multiple={false}
style={imageUploadStyle}>
<div>Drag and drop or click to select a 550x550px file to upload.</div>
</Dropzone>
https://toddmotto.com/react-create-class-versus-component/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With