I'm encountering an issue with a React component where I'm implementing functionality to upload images. When the user selects an image using the file input, the selected image is displayed within a popup. However, when the user clicks on the closePopup button, the selected image is cleared, preventing it from being saved to the backend.
const openPopup = () => {
setIsPopupOpen(true);
};
const closePopup = () => {
setIsPopupOpen(false);
};
const handleImageChange = (e, index) => {
const file = e.target.files[0];
if (file) {
const imageUrl = URL.createObjectURL(file);
setImages(`img${index}`, imageUrl);
}
};
<button
className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded"
onClick={openPopup}
>
Open Popup
</button>
{isPopupOpen && (
<div className="fixed inset-0 z-50 flex items-center justify-center overflow-auto bg-gray-800 bg-opacity-75">
<div className="bg-white rounded-lg p-8">
<h2 className="text-xl font-semibold mb-4">Upload Image</h2>
<input
type="file"
id="img2"
className="block w-full border-gray-400 p-2 rounded"
accept="image/*"
onChange={handleImageChange}
/>
<button
className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded"
onClick={closePopup}
>
Close
</button>
</div>
</div>
i want when user click on closepop still selected image should present there so that it saved at MongoDB else as of now when i click on close popup it clear the field and that image not saving on mongodb