I've edited the original post as it had two separate problems and ultimately AKX in the comments helped me solve what the real problem was.
I'm trying to do an image preview for multiple images using appendChild as shown in the MDN docs, but when I go to submit the form and want to reset the page I'm noticing that using appendChild can be kind of an anti-pattern in React. I want to come up with a solution where I store an array of image tags that I could then just set to empty on submit to clear the page, as opposed to having to query select them all with document and remove.
With the code below I'm only rendering the first image out of a batch upload of multiple files. Single image uploads one after another work fine.
const previewMainImages = (e) => {
const files = Object.values(e.currentTarget.files)
if (mainImageFiles.length + 1 > 10) {
setErr(errMessage = 'Only 10 images can be uploaded here')
return
}
function readAndPreview(file) {
var reader = new FileReader();
reader.onloadend = () => {
var image = <img src={reader.result} alt={file.name}/>
setMain(mainImageFiles = [...mainImageFiles, file])
setMainImages(mainImages.concat(image))
}
reader.readAsDataURL(file);
}
if (files) {
files.forEach((f, i) => {
console.log(f)
readAndPreview(f)
});
}
}
.map(), which is what React cares about. Whatever you do inreader.onloadendis out of React's "reach", as it were. You will need to do the asynchronous stuff (reading the files) separately and stuff the results into state.{file: ..., preview: ...}in state.