JSFiddle - React, Tailwind, and code Playground
HTML
<div class="container">
<label for="file" id="file-upload">Select an Image</label>
<input type="file" name="file-upload" id="file" accepts=".jpg, .jpeg, .png" multiple>
<div class="preview">
<img id="file-preview">
</div>
</div>
CSS
body{
height: 100vh;
}
.container{
width: 100vw;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
}
label{
width: auto;
display: block;
align-self: center;
background: hotpink;
padding: 15px 20px;
border-radius: 5px;
font-weight: bold;
color: white;
text-transform: uppercase;
cursor: pointer;
font-family: Avenir, Helvetica, Arial, sans-serif;
font-size: 11px;
box-shadow: 0 3px 10px 0 rgba(0,0,0,0.2), 0 6px 20px 0 rgba(0,0,0,0.19);
transition: box-shadow ease 0.25s;
}
label:active{
box-shadow:none;
}
input#file {
width: 0;
height: 0;
}
.preview{
/* border: 1px solid red; */
}
.preview img{
background:red;
width: 50px;
height: 50px;
display: none;
}
JavaScript
let uploadButton = document.querySelector('input')
uploadButton.addEventListener('change', (e)=>{
const currFiles = e.target.files
if(currFiles.length > 0){
let src = URL.createObjectURL(currFiles[0])
let imagePreview = document.getElementById('file-preview')
imagePreview.src = src
imagePreview.style.display = "block"
}
})
//e.target gets the current node element being clicked, e.target.files returns a fileList which is an Object that contains information about the image we uploaded
//adding [0] means we want to get the first element from the fileList