DEV Community

Cover image for Frontend Shorts: How to Read Content From The File Input in React
Ilona Codes
Ilona Codes

Posted on • Originally published at Medium

Frontend Shorts: How to Read Content From The File Input in React

As you know, I prefer learning to code by doing things. So, today I want to share the feature I have implemented for the app is the reading of the content from the uploaded (local) *.csv file from the user.

To do so without a server or any back-end β€” is a challenge.

To make things work properly in React+Redux, I have created the following component:

The FileReader object lets web apps asynchronously read the contents of files stored in the user’s computer, using File or Blob objects to specify the file or data to read.

Then the readAsText method is used to read the contents of the specified File or Blob. When the read operation is complete, the state is changed to done; the onloadend is triggered, and, if fileReader.result is not null, the constant content contains the contents of the file as a text string.

Any load event of fileReader object sets the result value asynchronously, and according to the code snippet above the fileReader.onloadend callback can access the result of uploaded file by the user.

If you would like to know more, then read about FileReader, File, and readAsText at MDN

Thank you for reading!

I hope you find the post useful and will still be looking forward to new updates there.


Photo by Kolar.io on Unsplash

Top comments (3)

Collapse
 
jonathangraf profile image
jonathangraf

The handleFileRead function doesn't utilize it's argument (e) to assign the result to the variable "content". Is that on purpose?
And why are you not using the useCallback hook? Is it not useful in this scenerio?
I am not judging just truly curious. I am getting warnings about the performance of my code....

Collapse
 
lorenzofelletti profile image
Lorenzo Felletti

That was exactly what I needed! Thanks a lot, beautiful article!

Collapse
 
onerishav profile image
Rishav Sarkar • Edited

Thank you man helps a lot