How to reset ReactJS file input
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.
Wait! You also need to increment inputKey
in your state to ensure it resets:
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
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:
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!
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:
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!
Was this article helpful?