简体   繁体   中英

Drag and drop area with react-dnd

I'm trying to create a drag and drop area for uploading a single picture and I want to pass it to the application state in the base64 encoded URL using a function onDrop .

import React from "react";
import {useDrop} from 'react-dnd'


export default function MyDropTarget(props) {
    const [drop] = useDrop({
        accept: "box",
        collect: (monitor) => {
                const res = monitor.getItem();
                if (res && res.files) {
                    const reader = new FileReader();
                    reader.onloadend = () => props.onDrop(reader.result);
                    reader.readAsDataURL(res.files[0]);
                }
        },

    });
    return (
        <div ref={drop}>
            Drag item here
        </div>);
};

That's how I use this component:

<DndProvider backend={HTML5Backend}>
  <MyDropTarget style={{height: "100px", width: "100px"}} onDrop={updateImage}/>
</DndProvider>

Since I am new to react-dnd I am having some problems. I got such an error TypeError: Failed to execute 'readAsDataURL' on 'FileReader': parameter 1 is not of type 'Blob'.
I think I do not understand the structure of monitor.getItem() correctly and will be grateful for any hint how to fix it.

My guess is that you need to make sure res.files[0] has a value (not undefined or null ).

 if(res.files[0]){
  reader.readAsDataURL(res.files[0]);
 }

You may also try to check the type of res.files[0] is if that doesn't help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM