It looks like you want to keep a list/array of HTML-file objects, but your state is initialized with a string (" ") instead of an array.
Because of that, when you do things like [...prevHtmlFile], .map, or .filter, React will throw errors such as “prevHtmlFile.map is not a function” or “Cannot spread non-iterable instance”.
Below is a “fixed” and slightly polished version of your state logic. I’m going to assume:
• You may eventually store more than one field for each file (e.g. file, preview, name, etc.), so each element will be an object.
• If you only need a single string per file, you can simplify each object to just that string.
// 1️⃣ State: start with an empty array
const [htmlFiles, setHtmlFiles] = useState([]);
/* ------------------------------------------------------------------ */
/* 👇🏼 CRUD helper handlers */
/* ------------------------------------------------------------------ */
// 2️⃣ Add a new HTML file “slot”
const handleAddHtmlFile = () => {
// You could push an empty object, or a default object
setHtmlFiles(prev => [...prev, { file: null }]);
};
// 3️⃣ Remove an HTML file by index
const handleRemoveHtmlFile = (index) => {
setHtmlFiles(prev => prev.filter((_, i) => i !== index));
};
// 4️⃣ Update the data of one file (index, field, value)
const handleHtmlFileChange = (index, field, value) => {
setHtmlFiles(prev =>
prev.map((item, i) =>
i === index ? { ...item, [field]: value } : item
)
);
};
Tiny demo of how you might wire it up in JSX:
{htmlFiles.map((item, idx) => (
<div key={idx}>
<input
type="file"
accept=".html"
onChange={e => {
const fileObj = e.target.files?.[0];
handleHtmlFileChange(idx, "file", fileObj);
}}
/>
<button onClick={() => handleRemoveHtmlFile(idx)}>Remove</button>
</div>
))}
<button onClick={handleAddHtmlFile}>Add another file</button>
Why these changes?
-
useState(" ") → useState([])
State shape should match how you plan to treat it (array).
-
htmlFile → htmlFiles (optional but more semantic when it holds many).
-
Each handler uses the functional form (prev => …). That’s already how you were doing it—good job.
Feel free to adapt the default object shape inside handleAddHtmlFile to whatever fields you really need (e.g. { name: "", content: "" }).
If any of these assumptions don’t match your use case, let me know and we can tweak the pattern further!