How to Set an Upload File Size Limit in a React Application

Uploading files is a common feature in web applications, but allowing users to upload large files can lead to performance issues and storage challenges. In this tutorial, I’ll show you how to implement a file size limit in a React application to ensure users cannot upload files that exceed a specified size.

Setting an Upload File Size Limit in ReactJS

First, create a React application if you don’t have one. Follow the instructions here.

1.Using the useState Hook:

Use the useState hook to manage the state within a functional React component. We will use useState to handle two states: the selected file and any error messages.

import React, { useState } from 'react';

const App = () => {
  const [file, setFile] = useState(null);
  const [error, setError] = useState('');
  • The file variable holds the currently selected file, initially set to null because no file is selected.
  • The setFile function updates the file state.
  • The error variable holds any error message related to the file upload process, initially set to an empty string.
  • The setError function updates the error state.
2.Handling File Change:

The handleFileChange function triggers when a user selects a file from the file input. It checks the size of the selected file and updates the state accordingly.

const handleFileChange = (event) => {
  const selectedFile = event.target.files[0];
  const fileSizeLimit = 5 * 1024 * 1024;

  if (selectedFile && selectedFile.size > fileSizeLimit) {
    setError('File size exceeds the 5MB limit.');
    setFile(null);
  } else {
    setError('');
    setFile(selectedFile);
  }
};
  • The function retrieves the file object from the file input field and defines the maximum allowed file size as 5MB.
  • If the selected file exceeds the size limit, the function sets an error message and resets the file state to null.
  • If the file size is within the limit, the function clears the error message and updates the file state with the selected file.
3.Handling File Submit:

The handleSubmit function is triggered when the form is submitted. It prevents the default form submission behavior and proceeds with the file upload if a valid file is selected.

const handleSubmit = (event) => {
  event.preventDefault();
};

preventDefault() prevents the default behavior of the form submission, which would cause the page to reload.

4.Rendering the Component:

You can apply them in the return() function which provides the structure for your website and makes it responsive.

5.Output:

these are the outputs,

No Selected file

no file chosen- image

Selected file size is more than the limit

selected file size more than limit- image

Selected File

file selected- image

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top