1
const passFromPicToUpload = (e) =>{
        hiddenFileInput.current.click();
        console.log("one")
    }

const handleProfilePicUpload = (e) =>{
    console.log("two")

    if(e.target.files[0]){
        setImage(e.target.files[0]);
        
    }
}

 return (
     <div className="profile">
      <div className="imageContainer" >
       <a href="#" onClick={passFromPicToUpload}>
        {
          profile.avatarUrl?<Image src={profile.avatarUrl} className="profile__image"  /> :<Image src="https://i.sstatic.net/l60Hf.png" className="profile__image" /> 
        }
       </a>
      </div>   
     <input type="file" ref={hiddenFileInput} onChange={handleProfilePicUpload} style={{display:'none'}} /> 

 </div>
)

So basically the file choosing window is showing but after I choose a pic the "handleProfilePicUpload" is not firing.

3
  • Please show us the whole component. Also, why is that 'display: none'? Commented Feb 6, 2021 at 13:32
  • 1
    Why don't you simply use label? Commented Feb 6, 2021 at 13:34
  • Did the below answers help you? If so, please accept or vote Commented Feb 27, 2021 at 18:56

3 Answers 3

3

You trying to simulate onChange by click event. Change the listener to onClick:

<input onClick={handleProfilePicUpload} .. />

A cleaner solution would be using a label:

<input type="file" id="file" style="display:none;">
<label for="file">
   <a>Image</a>
</label>

Sign up to request clarification or add additional context in comments.

Comments

1

You can simply use a label:

.hidden {
  display: none;
}
<input type="file" name="file" id="my-file" class="hidden">
<label for="my-file">
   <img src="https://picsum.photos/200/300" width="100" height="100"> 
</label>

It will work exactly as an HTML file input tag works.

So, you can do:


function onFileChange(e) {
  setImage(e.target.files)
}

// ...

<label
  htmlFor="my-file"
  title="Click to choose a file"
>
  <img src="https://picsum.photos/200/300" width="100" height="100">
</label>
<input
  type="file"
  id="my-file"
  className="hidden"
  onChange={onFileChange}
/>

Comments

0
<input
   type="file"
   accept="image/*"
   name="pic"
   onChange={(e: any) => {}}
   style={{ display: 'none' }}
   ref={fileRef}
/>

If you hide the input through styles onChange does get fired but make sure your component is mounted before your call click through the reference

1 Comment

Code-only answers are generally considered low-quality answers on Stack Overflow. This answer could be improved with an explanation as to how this solves OP's problem presented in the question.

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.