Clearing a file input in React
A small React tool I’ve been working on required me to clear a file upload field after the form was submitted. Since a file input’s value cannot be changed through JavaScript (imagine a script automatically setting a field to /etc/passwd
), the field would have to be rerendered entirely to clear it.
This proved very easy to do in React. The key
attribute, if changed, will force an element to be rerendered. Therefore, we can simply do this:
1 | export default class FileUpload extends React.Component { |
Now every time the onDelete
handler is called, the key will update with a new timestamp and force a rerender.