I am using react.js, I have a form, that I am submitting to an API and the form works fine up to the point where I want to clear the fields. Well actually one field in particular, the file input. I can't get it to reset back to "No File Selected", I've tried creating a files= attribute and controlling it through the state, and everything. Nothing is working, what am I missing?
I only want to reset it when there has been a successful submission.
What is the right approach to this.
<input
type="file"
name="js-case-upload"
className="form-control-static"
filename={this.state.files}
accept="image/*"
onChange={ this._onChangeFileInput }
/>
I am using react.js, I have a form, that I am submitting to an API and the form works fine up to the point where I want to clear the fields. Well actually one field in particular, the file input. I can't get it to reset back to "No File Selected", I've tried creating a files= attribute and controlling it through the state, and everything. Nothing is working, what am I missing?
I only want to reset it when there has been a successful submission.
What is the right approach to this.
<input
type="file"
name="js-case-upload"
className="form-control-static"
filename={this.state.files}
accept="image/*"
onChange={ this._onChangeFileInput }
/>
Share
Improve this question
edited May 27, 2016 at 5:20
chris
asked May 27, 2016 at 4:48
chrischris
37k53 gold badges147 silver badges256 bronze badges
1
- 1 Can you post your code? – socialpiranha Commented May 27, 2016 at 5:15
3 Answers
Reset to default 8Considering the input
have id
myFile
, then the file can be reset by vanilla javascript like the following:
document.getElementById("myFile").value = "";
const Upload = ({ onUpload }) => {
const ref = useRef();
const onChange = (e) => {
onUpload(e.target.files, () => {
ref.current.files = null;
});
};
return <input ref={ref} onChange={onChange} type="file" />;
};
I put a callback once I uploaded the file. On the callback I just set my files to null.
Consider adding a ref="file"
to you file input, and after submitting the data, use something like this.refs.file.value = ''
.
EDIT:
Even a simpler solution: https://jsfiddle/n06qk9h4/