JSFiddle - React, Tailwind, and code Playground
by thanhansoft
HTML
</head>
<body>
<div class="hero">
<label for="input-file" id="drop-area">
<input type="file" accept="image/*" class="input-file" hidden>
<div id="img-view">
<img src="icon.png">
<p>Drag and drop or click here<br>to upload image</p>
<span>Upload any images from desktop</span>
</div>
</label>
</div>
<div class="hero">
<label for="input-file" id="drop-area">
<input type="file" accept="image/*" class="input-file" hidden>
<div id="img-view">
<img src="icon.png">
<p>Drag and drop or click here<br>to upload image</p>
<span>Upload any images from desktop</span>
</div>
</label>
</div>
</body>
</html>
CSS
* {
margin: 0;
padding: 0;
font-family: 'Poppins', sans-serif;
box-sizing: border-box;
}
.hero {
display: flex;
align-content: center;
justify-content: center;
}
#drop-area {
width: 500px;
height: 300px;
padding: 30px;
background: #fff;
text-align: center;
border-radius: 20px;
}
#img-view {
width: 100%;
height: 100%;
border-radius: 20px;
border: 2px dashed #bbb5ff;
background: #f7f8ff;
background-position: center;
background-size: cover;
}
#img-view img {
width: 100px;
margin-top: 25px;
}
#img-view span {
display: block;
font-size: 12px;
color: #777;
margin-top: 15px;
}
JavaScript
const dropArea = document.getElementById("drop-area");
const inputFile = document.querySelector("input-file");
const imageView = document.getElementById("img-view");
inputFile.addEventListener("change", uploadImage);
function uploadImage() {
let imgLink = URL.createObjectURL(inputFile.files[0]);
imageView.style.backgroundImage = `url(${imgLink})`;
imageView.textContent = "";
imageView.style.border = 0;
}
dropArea.addEventListener("dragover", function(e) {
e.preventDefault();
});
dropArea.addEventListener("drop", function(e) {
e.preventDefault();
inputFile.files = e.dataTransfer.files;
uploadImage();
});