I am working on a React project ("react": "^16.13.1") and handling file uploads using an . However, I am encountering the following error in the console:
Is this error happening due to the deprecation of CRA?
react-dom.development.js:1571 Uncaught InvalidStateError: Failed to set the 'value' property on 'HTMLInputElement': This input element accepts a filename, which may only be programmatically set to the empty string.
at HTMLInputElement.set [as value] (react-dom.development.js:1571:1)
at SanitizedInputContext.js:30:1
at HTMLDocument.handleGlobalInput (SanitizedInputContext.js:37:1)
Issue:
- I am trying to preview the uploaded file using URL.createObjectURL().
- When I select a file, it should update the state and display a preview.
- However, after selecting a file, the error appears, and the preview does not always update as expected.
Version:
"react": "^16.13.1",
"react-dom": "^16.13.1",
"react-scripts": "^3.4.1",
import React, { useState } from "react";
const FileUpload = () => {
const [basicDetails, setBasicDetails] = useState({});
const [docPreview, setDocPreview] = useState({
pan_preview: "",
aadhaar_preview: "",
bank_preview: "",
education_preview: "",
});
const handleFileChange = (event) => {
const { files, name } = event.target;
if (files && files.length > 0) {
const selectedFile = files[0];
const newUrl = URL.createObjectURL(selectedFile);
setBasicDetails((prev) => ({
...prev,
[name]: newUrl,
}));
setDocPreview((prev) => ({
...prev,
...(name === "document_pan_card" && { pan_preview: newUrl }),
...(name === "document_aadhaar_card" && { aadhaar_preview: newUrl }),
...(name === "document_bank_passbook" && { bank_preview: newUrl }),
...(name === "document_education_proof" && { education_preview: newUrl }),
}));
}
};
return (
<div className="container">
<div className="col-3">
<label htmlFor="document_pan_card">Pan Card</label>
<div className="custom-file mb-4">
<input
type="file"
accept="image/*"
onChange={handleFileChange}
className="custom-file-input"
name="document_pan_card"
id="document_pan_card"
aria-describedby="document_pan_card"
/>
<label className="custom-file-label" htmlFor="document_pan_card">
Upload Document
</label>
</div>
{/* Document Preview */}
<div className="form-group row justify-content-around">
{docPreview.pan_preview && (
<div className="align-items-center justify-content-center mb-4">
<img
src={docPreview.pan_preview}
alt="PAN Preview"
width="200"
height="200"
style={{ border: "1px solid #ccc", padding: "5px" }}
/>
</div>
)}
</div>
</div>
</div>
);
};
export default FileUpload;