EN
React - file input example
3 points
In this article we would like to show you how to upload files in React.
Below example shows simple Form
with <input type="file" />
element that helps us to select file from computer and upload it using FormData
class and Ajax request.
Runnable example:
xxxxxxxxxx
1
//Note: Uncomment import lines during working with JSX Compiler.
2
// import React from 'react';
3
4
const Form = () => {
5
const handleSubmit = (e) => {
6
e.preventDefault();
7
const formData = new FormData(e.target);
8
fetch("/example/upload", {
9
method: "POST",
10
body: formData,
11
})
12
.then((response) => {
13
response.text().then((text) => console.log(text));
14
})
15
.catch((error) => {
16
console.error("File upload error!");
17
});
18
};
19
return (
20
<form onSubmit={handleSubmit}>
21
<label htmlFor="userfile">Upload file:</label>
22
<input type="file" id="userfile" name="userfile"></input>
23
<input type="submit" value="Submit!"></input>
24
</form>
25
);
26
};
27
28
const root = document.querySelector("#root");
29
ReactDOM.render(<Form />, root);