Explain Codes LogoExplain Codes Logo

How to reset ReactJS file input

javascript
react
file-input
reset
Alex KataevbyAlex Kataev·Dec 8, 2024
TLDR

Resetting a ReactJS file input? It's all about changing its key attribute. The secret here is that the key's state change makes the component remount, thus clearing away the input.

<input type="file" key={inputKey} />

Wait! You also need to increment inputKey in your state to ensure it resets:

const [inputKey, setInputKey] = useState(0); setInputKey(inputKey + 1); // Strictly "inputKey++" isn't real math, but hey, it works!

Clearing input without a re-render

Want to wipe away that input but don't feel like re-rendering an entire component? No problem! Speaking directly to the DOM element using its ref attribute will get the job done:

Crafting a ref to the file input

const fileInputRef = useRef(); // Keep Refs not Pet, they don’t bite! const handleReset = () => { // BOOM! It's gone. It's like Terminator but for files. fileInputRef.current.value = ''; }; return ( <> <input type="file" ref={fileInputRef} /> <button onClick={handleReset}>Reset</button> // Beware! Click me and your file's doom is sealed!!! </> );

Scheduler to ensure upload event consistency

To be sure the upload event always gets an invite to the party, even when the same file is chosen, clear out the input value:

const handleChange = (event) => { // You'll process the file here event.target.value = null; // Null, the loneliest number. It erases anything it touches. };

Re-render with a unique key

But if you’re more into ref nudging, you can still nudge the component to re-render with a fresh key — like getting a new identity in a movie!

const forceResetKey = () => Math.random().toString(); // You’re very special random key! <input type="file" key={forceResetKey()} onChange={yourUploadHandler} />

Techniques for legacy browsers

Now, we know not everyone's using the latest and greatest - so for those on older browsers like our good old IE9 or IE10, clear your file inputs without fear!

For those who traveled back in time

For the classics which lack support for setting input.value to null or '', it's just a matter of an old switcheroo:

const resetFileInputForLegacyBrowsers = () => { // Older Browsers: We've got your back! const oldInput = document.getElementById("myFileInput"); const newInput = document.createElement("input"); newInput.type = "file"; newInput.id = oldInput.id; oldInput.parentNode.replaceChild(newInput, oldInput); // Hide that old thing and bring out something shiny! };

Watch your step! Common pitfalls

Despite how straight the road may seem, you might find a few potholes on your way of resetting file inputs in React.

Getting the reset timing right

Don't just stick your reset logic in any dark corner. With top-class placement, you avoid clumsy not-reset behaviour or user interface lags.

Deal with the duplicate file issue

Remember, cleaning the slate means an identical file can be selected anew. Some browsers, the bashful types, won't make a peep (fire a change event) when that happens. To coax them out, clear their cache and they'd announce every file choice.

Clearing React's state

If your secret files are sitting in React state, remember to swipe it all clean in sync with cleaning the input value.

Any thoughts, questions, desires?

We are here to help! Further assist, clarify, and help with these demystified coding methods. Stumble upon specific use case issues? Or have other challenges in mind? Pop up and let's untangle it together!