0
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.stack.imgur.com/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.

dodododo97
  • 165
  • 1
  • 10

3 Answers3

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>
Dennis Vash
  • 50,196
  • 9
  • 100
  • 118
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}
/>
Ajeet Shah
  • 18,551
  • 8
  • 57
  • 87
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

Sehrish Waheed
  • 1,230
  • 14
  • 17
  • 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. – codewario May 31 '22 at 14:24