When creating a form that allows users to upload images, it is sometimes necessary to impose restrictions on the file size. For instance, let’s say we want to limit the image size to 3MB. In this blog post, we will explore how to implement this requirement in a React application using the onChange event.

To begin, we have a form with a file input box like this:

<input
 name='image'
 type='file'
 accept='image/*'

To ensure that the uploaded image is smaller than 3MB, we can add an onChange event handler to the input element. Here’s an example of how this can be done:

<input
 name='image'
 type='file'
 accept='image/*'
 onChange={(event) => {
 if (event.target.files && event.target.files[0]) {
 if (event.target.files[0].size > 3 * 1000 * 1024) {
 alert('Maximum size allowed is 3MB')
 return false
 }
 setImage(event.target.files[0])
 setImageURL(URL.createObjectURL(event.target.files[0]))
 }
 }}
/>

In the onChange event handler, we check if the files property exists in the event.target object and if the first file has been selected. If these conditions are met, we can proceed with checking the file size.

The file size is checked against the limit of 3MB, which is represented as 3 multiplied by 1000 and then by 1024. If the size exceeds this limit, an alert message is displayed to notify the user.

If the file size is within the allowed limit, we can proceed to set the image state and the corresponding image URL using the setImage and setImageURL functions, respectively. This allows us to display a preview of the uploaded image or perform any additional operations required.

In conclusion, by implementing the onChange event handler and adding the necessary checks, we can ensure that the uploaded image remains within the specified size limit. This helps maintain an optimized user experience and ensures an efficient handling of image uploads.