Search code examples
reactjsreact-dropzone

react-dropzone preview property missing


Tried almost everything but, couldn't get it working? Can anyone point out what I'm missing? Also, I looked at other stack overflow post nothing seem to be working for me.

Don't know why the file.preview is missing but it seems to work well for others. Is it because of the component model is used? Should I go with functional component?

constructor() {
 super();
  this.onDrop = (files) => {
    console.log(files)
    this.setState({ files })
  };
  this.state = {
    files: []
  };
}

renderPreviewImg(files) {
  console.log(files)
  const img = {
    display: 'block',
    width: 'auto',
    height: '100%'
  };

  const thumb = {
    display: 'inline-flex',
    borderRadius: 2,
    border: '1px solid #eaeaea',
    marginBottom: 8,
    marginRight: 8,
    width: 100,
    height: 100,
    padding: 4,
    boxSizing: 'border-box'
  };

  const thumbInner = {
    display: 'flex',
    minWidth: 0,
    overflow: 'hidden'
  };

  const thumbs = files.map(file => (
    <div style={thumb} key={file.name}>
      <div style={thumbInner}>
        <img
          src={file.preview}
          style={img}
          alt="review"
        />
      </div>
    </div>
  ));
  return thumbs;
}

<Dropzone
  onDrop={this.onDrop}
>
  {({ getRootProps, getInputProps }) => (
    <section className="container">
      <div {...getRootProps({ className: 'dropzone' })}>
        <input {...getInputProps()} />
        <p>Drag 'n' drop some files here, or click to select files</p>
      </div>
      <aside style={thumbsContainer}>
        {this.renderPreviewImg(this.state.files)}
      </aside>
    </section>
  )}
</Dropzone>

Console.log of files

Missing preview image


Solution

  • You can use this method

    <img src={URL.createObjectURL(file[0])} />
    

    If you have more than one file then loop through files and return above statement for each file.

    <Dropzone
      onDrop={this.onDrop}
    >
      {({ getRootProps, getInputProps }) => (
        <section className="container">
          <div {...getRootProps({ className: 'dropzone' })}>
            <input {...getInputProps()} />
            <p>Drag 'n' drop some files here, or click to select files</p>
          </div>
          <aside style={thumbsContainer}>
            {this.state.files.map(file=>{
            return <img src={URL.createObjectURL(file[0])} />
            })}
          </aside>
        </section>
      )}
    </Dropzone>