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=".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.
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/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.
Share Improve this question asked Feb 6, 2021 at 13:26 dodododo97dodododo97 1651 silver badge11 bronze badges 3- Please show us the whole ponent. Also, why is that 'display: none'? – yovchokalev Commented Feb 6, 2021 at 13:32
- 1 Why don't you simply use label? – Ajeet Shah Commented Feb 6, 2021 at 13:34
- Did the below answers help you? If so, please accept or vote – Ajeet Shah Commented Feb 27, 2021 at 18:56
3 Answers
Reset to default 3You 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>
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}
/>
<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 ponent is mounted before your call click through the reference