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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
export default class FileUpload extends React.Component {
constructor(props) {
super(props);
this.state = {
file: null,
inputKey: Date.now()
};
}
//...
onDelete() {
this.setState({
file: null,
inputKey: Date.now()
});
if (this.props.onChange) this.props.onChange(null);
}
render() {
return (
//...
<input
type="file"
key={this.state.inputKey}
//...
/>
);
}
}

Now every time the onDelete handler is called, the key will update with a new timestamp and force a rerender.