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.
- We hide the <input type=”file” /> using CSS, so that the user cannot see the default file upload control;
- We use React Ref to store a reference to the <input type=”file” /> element, so that we can call it programmatically later on;
- After the custom button is clicked, we programmatically trigger the default file input field;
- 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;
- This method is called after the user selects a file from his computer;
- We notify the parent component that the selected file is going to be processed;
- We get the selected file;
- We check if the format of the selected file is acceptable. If it is not acceptable, we notify the parent component of this;
- Otherwise, we pass the selected file to the parent component for further processing.