I have created an image upload thingamajig called ImageSelector as a reusable component. It's for a custom CMS where the user first selects a header image, then selects several images for a gallery.
So the top part of the form uses the <ImageSelector /> component and the bottom part of the form uses an array of the same component. But for some reason whenever I select an image using the second ImageSelector at the bottom of the form, it only changes the image for the first ImageSelector.
It surely can't be the components' state that is bound together as I've never experienced that to be a problem, so it must be something to do with the way the browser caches files right? My question is, how can I make a reusable image upload component in React and avoid this duplication behaviour?
ImageSelector component:
(styles removed for brevity)
import { useState } from "react";
import { AiFillCamera } from "react-icons/ai";
import styled from "@emotion/styled";
export default function ImageSelector({ placeholder, shape }) {
const [currentImage, setCurrentImage] = useState();
const [currentImageUrl, setCurrentImageUrl] = useState();
function handleChangeImage(e) {
setCurrentImage(e.target.files[0]);
setCurrentImageUrl(URL.createObjectURL(e.target.files[0]));
}
return (
<ProfileImage $shape={shape}>
<div>
<ProfileImageOverlay $image={!!currentImage}>
<Label htmlFor="selector-image" $image={!!currentImage}>
{placeholder ? placeholder : <AiFillCamera />}
</Label>
<input
id="selector-image"
type="file"
name="selector-image"
onChange={handleChangeImage}
/>
</ProfileImageOverlay>
{currentImage && (
<img src={currentImageUrl} alt="selected image" width="170px" height="170px" />
)}
</div>
</ProfileImage>
);
}
