React validate the file size before upload

In this tutorial, we will see how to validate the file size before uploading it in React.

When a file is selected in the form through input[type=”file”], we can add a check on the onChange event and get the file size and add the validations.

For example, in the below code, we have restricted the input to select only images, and that too with a size of 1 megabyte or less.

import React from "https://esm.sh/react@18.2.0";
import ReactDOM from "https://esm.sh/react-dom@18.2.0";

const App = () => {
  return (
    <input
      name="file-upload"
      type="file"
      accept="image/*"
      onChange={(event) => {
        if (event.target.files && event.target.files[0]) {
          if (event.target.files[0].size > 1 * 1000 * 1024) {
            console.log("File with maximum size of 1MB is allowed");
            return false;
          }

          // do other operation
        }
      }}
    />
  );
};

ReactDOM.render(<App />, document.querySelector("#root"));