Removing and Replacing Previews
What you'll learn: How to give users control to remove unwanted image previews and update the underlying file input state to match.
When users select files, they may change their mind or pick the wrong images. Just showing previews isn't enough—you need to let them remove or replace selections, keeping the UI and the actual file input synchronized.
The Challenge
The file input's files property is read-only. You can't directly modify it by removing specific files. This means when a user clicks "remove" on a preview, you need a workaround.
The Solution Pattern
For single-file inputs: Simply clear the preview and reset the file input:
removeButton.addEventListener('click', () => {
// Clear preview from DOM
previewImage.src = '';
previewContainer.style.display = 'none';
// Reset the file input
fileInput.value = '';
});
For multiple files: Maintain an array tracking which files to keep, then reconstruct the input using a DataTransfer object:
let selectedFiles = Array.from(fileInput.files);
function removeFile(index) {
// Remove from tracking array
selectedFiles.splice(index, 1);
// Remove preview from DOM
previewElements[index].remove();
// Rebuild file input
const dataTransfer = new DataTransfer();
selectedFiles.forEach(file => dataTransfer.items.add(file));
fileInput.files = dataTransfer.files;
}
Think of DataTransfer as a staging area where you rebuild the file list from scratch, excluding removed items.
Replacing vs. Removing
To replace: simply trigger a new file selection. The change event will fire, and you regenerate all previews from the new selection.
Key Takeaway: Since FileList is immutable, removing previews requires clearing the input (single files) or reconstructing it via DataTransfer (multiple files), always keeping your UI and file state synchronized.