Home ยป React dropzone example

React dropzone example

React dropzone is a hook to create an HTML 5 dropzone for files, We use this module for providing a way for users to upload a file by dragging and drop from their computer

You can download the working example of a react dropzone in the ReactJS Tutorial https://github.com/technostuf/reactjs-file-drop-example

  • Create a React application
  • Install react-dropzone library
  • Add code to the file
  • Run a React application
  • Add Styling & Image Preview

Create a React application

Create a React app using the below command

 npx create-react-app reactjs-file-drop-example

After running the above command system will create a new folder “reactjs-file-drop-example” so you need to move into that folder, use the below command to change the directory.

 cd reactjs-file-drop-example

Install react-dropzone library

After creating react app we need to install react-dropzone from npm or yarn

 npm install --save react-dropzone
 OR using yarn
 yarn add react-dropzone

Add code to the file

Create a component file to hold dropzone code separate from another component and put the below code into that file.

import React, { useCallback } from "react";
import { useDropzone } from 'react-dropzone';

const DropZoneComponent = () => {
    const onDrop = useCallback(acceptedFiles => {
        console.log(acceptedFiles);
    }, []);
    const {
        getRootProps,
        getInputProps
    } = useDropzone({
        onDrop
    });
    return (
        <>
            <h1>DropZone - Technostuf.com</h1>
            <div {...getRootProps()}>
                <input {...getInputProps()} />
                <div>Drag and drop your images here.</div>
            </div>
        </>
    )
}
export default DropZoneComponent;

After adding a code, you have called this component file into your code, in my case I am adding it to App.js

import DropZoneComponent from './DropZoneComponent';
import './App.css';

function App() {
  return (
    <div className="App">
      <DropZoneComponent />
    </div>
  );
}
export default App;

Run a React application

Run the React application using the following command

 npm start

After compilation, the program opens your browser and runs http://localhost:3000/

Output

Add Styling & Image Preview

import React, { useCallback, useMemo, useEffect, useState } from "react";
import { useDropzone } from 'react-dropzone';
const DropZoneComponent = () => {
    const [files, setFiles] = useState([]);
    const onDrop = useCallback(acceptedFiles => {
        setFiles(acceptedFiles.map(file => Object.assign(file, {
            preview: URL.createObjectURL(file)
        })));
    }, []);

    const images_preview = files.map(file => (
        <div key={file.name}>
            <img src={file.preview} alt={file.name} width='200' />
        </div>
    ));

    useEffect(() => () => {
        files.forEach(file => URL.revokeObjectURL(file.preview));
    }, [files]);
    const {
        getRootProps,
        getInputProps,
        isFocused,
        isDragAccept,
        isDragReject
    } = useDropzone({
        onDrop,
        accept: 'image/jpeg, image/png'
    });
    const baseStyle = {
        flex: 1,
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
        padding: '20px',
        borderWidth: 2,
        borderRadius: 2,
        borderColor: '#eeeeee',
        borderStyle: 'dashed',
        backgroundColor: '#fafafa',
        color: '#bdbdbd',
        outline: 'none',
        transition: 'border .24s ease-in-out'
    };
    const focusedStyle = {
        borderColor: '#2196f3'
    };
    const acceptStyle = {
        borderColor: '#00e676'
    };

    const rejectStyle = {
        borderColor: '#ff1744'
    };
    const style = useMemo(() => ({
        ...baseStyle,
        ...(isFocused ? focusedStyle : {}),
        ...(isDragAccept ? acceptStyle : {}),
        ...(isDragReject ? rejectStyle : {})
    }), [
        isFocused,
        isDragAccept,
        isDragReject
    ]);
    return (
        <>
            <div {...getRootProps({ style })}>
                <input {...getInputProps()} />
                <div>Drag and drop your images here.</div>
            </div>
            <aside>
                {images_preview}
            </aside>
        </>
    )
}

export default DropZoneComponent;

Output

react dropzone

You can download the working example of a react dropzone example

https://github.com/technostuf/reactjs-file-drop-example

Related Post

Leave a Comment

Your email address will not be published.

five × five =