Home > Software design >  How do I Prevent Opening in New Tab When Dragging Image/s in Div in React
How do I Prevent Opening in New Tab When Dragging Image/s in Div in React

Time:11-03

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>

CodePudding user response:

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)}
 >

CodePudding user response:

I hope following answer will help you

Please check the following code sandbox code, this solution is worked fine form me..

Working solution

https://codesandbox.io/s/react-hook-form-materialui-forked-n6r5l?file=/src/App.js

  • Related