Is there a way to attach input type="file" with a Button and hide the original implementation in react? Pressing the button invokes the file picker with hidden input type="file" tag.
2 Answers
You can do it using reference. I did it like this:
this.uploadRef = React.createRef();
.chat-image-upload {
display: none;
}
<input
type="file"
ref={(ref) => (this.uploadRef = ref)}
onChange={this.uploadImage}
accept="image/*"
data-field="groupImage"
className="chat-image-upload"
/>
I had an image instead of Button...so can change this accordingly
<img
src={uploadImage}
className="send-img-img"
alt="Send"
onClick={this.imageUploadClick}
/>
imageUploadClick = () => this.uploadRef.click();
uploadImage = async (e) => {
const fileName = e.target.value.toLowerCase();
if (
!fileName.endsWith(".jpg") ||
!fileName.endsWith(".jpeg") ||
!fileName.endsWith(".gif") ||
!fileName.endsWith(".png")
) {
alert("Please upload file type image only.");
return;
}
if (e.target.getAttribute("data-field") === "groupImage") {
const files = e.target.files;
if (!files.length) {
return alert("Please choose a file to upload first.");
} else {
const file = files[0];
}
}
};