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.