How do I Prevent Opening in New Tab When Dragging Image/s in Div in React

Viewed 787

I have succesfully implemented adding multiples images by clicking the browser button. My problem is when I wanted to drag image/images. It opens a new tab. How do I prevent it opening? I already put e.preventDefault() but its still opening.

Codesandbox is here CLICK HERE

    <Paper elevation={4} className={classes.mainContainer}>
      <div
        className={classes.dropzone}
        style={{
          border: "2px dashed #000000"
        }}
        onDragOver={(e) => e.preventDefault()}
        onDrop={(e) => uploadImage(e.currentTarget.files)}
      >
        <div>
        </div>
        <div>
          <h3 className={classes.dragHereText}>Drag & Drop Images here</h3>
          <p className={classes.or}>or</p>
          <Button
            size="small"
            variant="contained"
            component="label"
            color="primary"
          >
            <input
              type="file"
              accept="image/*"
              multiple
              className={classes.uploadInput}
              onChange={(e) => uploadImage(e.currentTarget.files)}
            />
            Browse files
          </Button>
        </div>
      </div>
    </Paper>
2 Answers

Firstly, you need to preventdefault on the onDrop hander too. Also, The event from the onDrop is different from the onChange event, so you will need to handle it differently. Here is an example:

const handleDrop = (e) => {
  // Note: preventDefault is on nativeEvent
  e.nativeEvent.preventDefault()
  if (!e) return;
  // Note: files are under nativeEvent.dataTransfer
  const files = e.nativeEvent.dataTransfer.files;
  const fileList = Array.from(files);
  const images = fileList.map((image) => ({
    imageName: image.name,
    imageFile: image
  }));
  console.log(images);
};

And pass the event in like this:

<div
  className={classes.dropzone}
  style={{
    border: "2px dashed #000000"
  }}
  onDragOver={(e) => e.preventDefault()}
  onDrop={(e) => handleDrop(e)}
 >
Related