0

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 2

2

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];
      }
    }
  };
Sign up to request clarification or add additional context in comments.

Comments

0

You can do something like this

HTML

<button type = "button" (click) = "openFile()"></button>
<input type = "file" id = "btnFile"></input>

TypeScript

openFile()
{
 document.getElementById("btnFile").click();
}

 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.