'How to create react js drag and drop file upload simply?

I want to create react js drag and drop file upload using class component !!

I have tried the normal file upload and it works fine, in addition I have tried using the react-drag-drop library, I can't access the file properties !!



Solution 1:[1]

react-dropzone uses React hooks to create HTML5-compliant React components for handling the dragging and dropping of files. react-dropzone provides the added functionality of restricting file types and also customizing the dropzone.

To install

npm install --save react-dropzone

Example of drag-and-drop component

import React, {useEffect, useState} from 'react';
import {useDropzone} from 'react-dropzone';

function App(props) {
  const [files, setFiles] = useState([]);
  const {getRootProps, getInputProps} = useDropzone({
    accept: 'image/*',
    onDrop: acceptedFiles => {
      setFiles(acceptedFiles.map(file => Object.assign(file, {
        preview: URL.createObjectURL(file)
      })));
    }
  });

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

  useEffect(() => {
    // Make sure to revoke the data uris to avoid memory leaks
    files.forEach(file => URL.revokeObjectURL(file.preview));
  }, [files]);

  return (
    <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}>
        {thumbs}
      </aside>
    </section>
  );
}

export default App

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Charfeddine Mohamed Ali