How to use a simple form for uploading files in React

It’s important to know that the task of enabling file uploads within a React application is fundamental for building different web applications. Such applications include image galleries and file management systems. In this Answer, our prime focus will be on the front-end aspect of the problem, talking through the creation of a basic React application that implements the feature of uploading files using a form.

Expected output

Here’s a visual of what to expect when we implement using a simple form for uploading files in React.

Step-by-step procedure

Here are the key steps to complete the task of implementing the file upload feature in React:

Step 1: Create a new React app

If we don’t have a React app already set up on our systems, we can create one by executing the following commands, one after the other:

npx create-react-app <folder-name>
cd <folder-name

Note: In the place of the <folder-name> tag/placeholder, we can write a directory name of our choice.

Step 2: Create a file upload component

Inside the /src folder of our React project, we’ll create a new component for the file uploading feature. This component contains the following code:

import React, { useState } from 'react';
import './fileupload.css';
function FileUpload() {
// Initializing selectedFile, setSelectedFile variables to display the details of the uploaded file in the console window
const [selectedFile, setSelectedFile] = useState(null);
// Initializing uploadSuccess, setUploadSuccess variables to display a message verifying that the upload is successful
const [uploadSuccess, setUploadSuccess] = useState(false);
// Initializing uploadFailed, setUploadFailed variables to display a message in case the file uploading operation is unsuccessful
const [uploadFailed, setUploadFailed] = useState(false);
// Initializing fileDetails, setFileDetails variables to store file information
const [fileDetails, setFileDetails] = useState(null);
// Initializing uploadProgress, setUploadProgress variables to track the upload progress
let [uploadProgress, setUploadProgress] = useState(0);
// Initalizing description, setDescription variables for adding description
const [description, setDescription] = useState('');
//Initializing uploadDateTime, setUploadDateTime variables for file upload date and time
const [uploadDateTime, setUploadDateTime] = useState('');
// Function to handle file input change
const handleFileChange = (event) => {
setSelectedFile(event.target.files[0]);
setFileDetails(null); //clears the file details from the webpage
};
// Function to handle form submission
const handleSubmit = (event) => {
//this function prevents default submission behavior
event.preventDefault();
if (selectedFile) {
// If the upload date and time is not entered, display an error message
if (!uploadDateTime) {
setUploadFailed(true); //initializing the upload failed variable to true
setUploadSuccess(false); //initializing the upload success variable to false
setFileDetails(null);
} else {
setUploadSuccess(false); //seting the upload success variable to false
setUploadFailed(false); //setting the upload failed variable to false
setUploadProgress(0); //setting upload progress to zero
// Simulate upload progress using a timeout
const uploadInterval = setInterval(() => {
if (uploadProgress < 100) { //checking if upload progress is less than 100
uploadProgress = uploadProgress + 10;
setUploadProgress(uploadProgress);
} else { //when the upload process reaches 100%
//the progress simulation interval is stopped
clearInterval(uploadInterval);
// Set upload success variable to true
setUploadSuccess(true);
//calculating the filesize in KBs, and setting its details (e.g., name, type, and filesize)
const fileSizeInKB = Math.round(selectedFile.size / 1024);
setFileDetails({
name: selectedFile.name,
type: selectedFile.type,
size: fileSizeInKB,
});
console.log('Uploaded File:', selectedFile);
}
}, 800); //Simulating upload progress every 0.8 seconds
}
} else {
setUploadFailed(true);
setUploadSuccess(false);
setFileDetails(null);
}
};
// Extra function to refresh the page after uploading the file
const refreshPage = () => {
setSelectedFile(null); // Clear the selected file
setFileDetails(null);
setUploadSuccess(false);
setUploadFailed(false);
setUploadProgress(0); //reset the upload progress to zero
window.location.reload();
};
// Render method within the return statement that triggers handleSubmit and handleFileChange
// Extra features implemented including printing the details of the file uploaded as well as a message showing that the upload was successful;
// In the case of no file being uploaded, a refresh button appears to try uploading files again
return (
<div>
<h2>Uploading files using a form in React</h2>
<form onSubmit={handleSubmit}>
<input className="title" id="fileInput" type="file" onChange={handleFileChange} />
{/*adding a description field for adding description of the file to be uploaded*/}
<input
className="description-input"
type="text"
placeholder="Enter description"
value={description}
onChange={(e) => setDescription(e.target.value)}
/>
{/* Adding input field for upload date and time */}
<font size= "3"> Upload date: </font><input
type="datetime-local"
value={uploadDateTime}
onChange={(e) => setUploadDateTime(e.target.value)}
/>
<button type="submit">Upload</button>
</form>
<div>
{uploadProgress > 0 && uploadProgress < 100 && (
<div>
<b className="right-shift">Uploading...</b>
<progress value={uploadProgress} max="100">
{uploadProgress}%
</progress>
</div>
)}
{uploadSuccess && (
<div>
<b className="right-shift">Uploaded successfully!</b>
<p>Details of file uploaded:</p>
<p>Name: {fileDetails.name}</p>
<p>Type: {fileDetails.type}</p>
<p>Description: {description}</p>
<p>Upload date and time: {uploadDateTime}</p>
<button onClick={refreshPage}>Remove File</button>
</div>
)}
{uploadFailed && <b className="right-shift">Upload failed. Please try again!</b>}
{uploadFailed && <button onClick={refreshPage}>Refresh</button>}
</div>
</div>
);
}
export default FileUpload;

In the code above, event handlers handleFileChange and handleSubmit are responsible for selecting a file and uploading it on the web page. Also, various state variables (e.g., uploadSuccess, uploadFailure, etc.) are updated to provide feedback to the user consisting of the file upload statusThis shows whether the file was uploaded successfully or not. and the details of the uploaded file. These handlers are triggered when the render method within the return statement is called when the React app starts.

Note: To read more about event handlers in React, check out this answer.

An interesting thing to note is that between the <form> tags, we’ve added two additional input fields that take the date and time of the file being uploaded, as well as its description. This gives the file upload form a more interactive feel when the user uploads a file for the first time.

Step 3: Import the file upload component

Next, we’ll import the component made in the step above in the App.js file (present in the /src directory as well) by writing the following code:

import React from 'react';
import './App.css';
import FileUpload from './FileUpload';
function App() {
//adding the contents of the FileUpload form inside <div> classes for better code organization
return (
<div className="App">
<header className="App-header">
<FileUpload />
</header>
</div>
);
}
export default App;

Note: We can replace ./FileUpload with any file name of our choice for our file upload component. We need to make sure that the file name in which we made the component is written properly in the import statement of the App.js file.

After incorporating the steps outlined above, we’ll finally start the React app with the npm start command.

Code Output

In this section, we can see what the React app with the file uploading feature will look like after incorporating all of the steps above. Feel free to add your own inputs to see the results!

The steps to fill the upload form can be seen in the slides below in which we start off with uploading the file in the first step, followed by adding a description for the file to be uploaded, and then setting the upload date of the file.

File upload form before uploading the file
File upload form before uploading the file
1 of 6

The fields in the form can be filled in any order we prefer, making sure that the date of upload is entered properly to avoid any possible errors as shown in the following slides. After filling out the form, we can verify that the files have been successfully uploaded as illustrated in the slides shown below.

canvasAnimation-image
1 of 2

Here, we right click the “Inspect” option to be able to navigate to the console section to see that the files have been successfully uploaded on the web page.

Conclusion

To summarize, the solution written above represents a simple React component that provides a basic file upload form. When we select a file and submit the form, it logs the selected file’s information to the console, verifying that frontend of the file upload process was successful. In a real-world application, we’re free to extend this code to handle file uploads to a server.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved