Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React-Dropzone image preview not showing

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>
    )
}

};

like image 471
megkadams Avatar asked Jul 13 '16 10:07

megkadams


People also ask

How do I preview an image in react dropzone?

Use URL. createObjectURL(file) on the files returned from the onDrop callback. See https://react-dropzone.js.org/#!/Previews for more info.

How do I show preview of an image before reacting in react JS?

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.

How do I upload pictures to react dropzone?

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> );

How do you use useDropzone?

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> .


1 Answers

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/

like image 144
megkadams Avatar answered Sep 28 '22 22:09

megkadams