Sometimes, we want to read a text file in React.
In this article, we’ll look at how to read a text file in React.
How to read a text file in React?
To read a text file in React, we can use the FileReader
constructor.
For instance, we write:
import React from "react";
export default function App() {
const showFile = (e) => {
e.preventDefault();
const reader = new FileReader();
reader.onload = (e) => {
const text = e.target.result;
console.log(text);
};
reader.readAsText(e.target.files[0]);
};
return (
<div>
<input type="file" onChange={showFile} />
</div>
);
}
to define the showFile
function that gets the selected file from e.target.files
.
Then we create a new FileReader
instance and assign it to reader
.
Next, we set reader.onload
to a function that runs when the file content is read.
We get the file content from e.target.result
.
We call reader.readAsText
to read the text from the selected file.
Finally, we add a file input and set its onChange
prop to showFile
so that showFile
runs when we select a file.
Conclusion
To read a text file in React, we can use the FileReader
constructor.