I'm having a good time trying to solve the weird behavior of my drag and drop in Chrome. There's no problem when I add files by clicking, the problem is when I drop them. When I drag and drop files sometimes works and sometimes fails. Checking out the problem, I realized that in certain occasions the e.dataTransfer.files
has a non empty FileList and works, but sometimes it doesn't, even when I'm selecting the same bunch of files. And sometimes, it shows a FileList with just one object even though I'm trying to add more than one file of PDF extension, and that only File object has no extension.
Here's the code...
const handleDrag = function (e) {
e.preventDefault();
e.stopPropagation();
if (e.type === "dragenter" || e.type === "dragover") {
setDragActive(true);
} else if (e.type === "dragleave") {
setDragActive(false);
}
};
// triggers when file is dropped
const handleDrop = async (e) => {
e.preventDefault();
e.stopPropagation();
setDragActive(false);
if (e.dataTransfer.files && e.dataTransfer.files[0]) {
await props.handleFilesToUpload(e.dataTransfer.files, props.filesToUpload, props.setFilesToUpload)
setDragActive(true)
}
e.dataTransfer.value = ""
};
// triggers when file is selected with click
const handleChange = async (e) => {
e.preventDefault();
setDragActive(false);
if (e.target.files && e.target.files[0]) {
await props.handleFilesToUpload(e.target.files, props.filesToUpload, props.setFilesToUpload)
setDragActive(true)
}
e.target.value = ""
};
// triggers the input when the button is clicked
const onButtonClick = (e) => {
if (e.type === "click") {
inputRef.current.click();
setDragActive(true);
}
};
const onModalClose = () => {
setDragActive(false)
props.handleClose()
}
return
...
<Grid item>
<form id={styles["form-file-upload"]} onDragEnter={handleDrag} onSubmit={(e) => e.preventDefault()}>
<input ref={inputRef} type="file" id={styles["input-file-upload"]} accept="application/pdf" multiple={true} onChange={e => handleChange(e)} onDragEnter={handleDrag}/>
<label id={styles["label-file-upload"]} htmlFor="input-file-upload" className={dragActive ? "drag-active" : ""}>
<div>
<button className={styles.uploadButton} onDragEnter={handleDrag} onChange={e => handleChange(e)} onClick={e => onButtonClick(e)}>
<ThemeProvider theme = {theme} >
<PictureAsPdfIcon fontSize='large' sx={{ pb: '10px', color: '#929395' }} />
<Typography variant='h6' fontWeight='bold' color='#5F5F5F' sx={{ mb: '10px' }}>
Seleccionar archivos para cargar
</Typography>
<Typography variant='body1' color='#929395'>
O arrastrar y soltar, copiar y pegar archivos.
</Typography>
</ThemeProvider>
</button>
</div>
</label>
{dragActive && <div id={styles["drag-file-element"]} onDragEnter={handleDrag} onDragLeave={handleDrag} onDragOver={handleDrag} onDrop={handleDrop} onClick={e => onButtonClick(e)}></div>}
</form>
</Grid>
...
I want to figure out what could be wrong to approach the solution.