Create a custom file upload control in React

We use <input type=”file”> to trigger the OS browser dialogue for the user to select a file from his computer for file upload. However, the look of the control is too primitive to be used directly in most applications and you cannot modify much about the control itself. In this article, I will share a way to create a custom file upload control in React.

Talk is cheap, show me the code.

Let’s go over some points in the code.

  1. We hide the <input type=”file” /> using CSS, so that the user cannot see the default file upload control;
  2. We use React Ref to store a reference to the <input type=”file” /> element, so that we can call it programmatically later on;
  3. After the custom button is clicked, we programmatically trigger the default file input field;
  4. The value of the file input field needs to be reset to null, otherwise, if we select the same file again, the file input field onChange event will not be fired;
  5. This method is called after the user selects a file from his computer;
  6. We notify the parent component that the selected file is going to be processed;
  7. We get the selected file;
  8. We check if the format of the selected file is acceptable. If it is not acceptable, we notify the parent component of this;
  9. Otherwise, we pass the selected file to the parent component for further processing.

Full-stack developer in Sydney

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store