I am trying to do a simple upload image layout on my app with a preview of the image. I followed a lot of tactics I found online either from Docs or YT Videos but none seem to work out. I get a weird behavior; as soon as I upload an image the preview of my uploaded image is seen for <1 sec. and disappears. Here is my component:
export const ChangeBackgroundImage = () => {
const [files, setFiles] = React.useState<File | null>(null);
const [createObjectURL, setCreateObjectURL] = React.useState<any>(null);
const [src, setSrc] = React.useState<any>(null);
const uploadToClient = (event: React.ChangeEvent<HTMLInputElement>) => {
if (event.target.files && event.target.files[0]) {
const i = event.target.files[0];
setFiles(i);
setCreateObjectURL(URL.createObjectURL(i));
const reader = new FileReader();
reader.onload = function () {
if (typeof reader.result === 'string') {
console.log('Hello World');
setSrc(reader.result);
}
return;
}
if (filesNew !== null) {
reader.readAsDataURL(filesNew[0]);
}
}
};
return (
<div className={style.change_bg}>
<h3>Change Background Image</h3>
<p className={style.change_bg_descP}>
Select A New Image And Upload It!
</p>
<div className={style.change_bg__form_div}>
<UploadImageSVG width={40} height={40} color={Colors.blue_med} />
{/* <input
type="file"
accept='image/*'
name='fileUpload'
id='fileUpload'
onChange={( event ) => {
// onFileChange(event);
if (event?.target?.files?.[0]) {
const file = event.target.files[0];
if (file && file.type.substring(0, 5) === "image") { setImage(file) }
else { setImage(null) }
}
}}
hidden
/> */}
<input type="file" name='image' accept='image/*' onChange={uploadToClient} />
</div>
<section className={style.handleImageDeletion}>
<FolderSVG width={20} height={20} color={Colors.blue_med} />
{src && <Image src={src} alt='Some Image' width={100} height={100} />}
{src && console.log(src)}
{files && files.name}
</section>
</div>
)
}
Any help would be appreciated.
Next JS Version: ^13.5.4, React & React-Dom: 18.2.0
Found the solution to my problem myself. Posting it for someone else if they struggle.
Working on NextJS the problem was that in non-page components for some reason the file input does not work. I wanted to have a separate component for this action in my application. Eventually I just made a separate page to my application and works fine. This might be a bug or something, I don't know.
And the real problem was that even with the simple input:
<input type="file" accept="image/*" onChange=[...] />
It was not registering the file. Kind of weird but ok.