Text File Download in React

Kayathiri Mahendrakumaran
Frontend Weekly
Published in
1 min readNov 18, 2019

Here, we will see how to download a text file using React JS framework.

Go through the following steps to for creating a React application to download a text file.

Creating react app

To create a project: Run

npx create-react-app download-app
cd download-app
npm start

Download Text file

Add the following code to App.js

class MyApp extends React.Component {
downloadTxtFile = () => {
const element = document.createElement("a");
const file = new Blob([document.getElementById('input').value],
{type: 'text/plain;charset=utf-8'});
element.href = URL.createObjectURL(file);
element.download = "myFile.txt";
document.body.appendChild(element);
element.click();
}
render() {
return (
<div>
<input id="input" />
<button onClick={this.downloadTxtFile}>Download</button>
</div>
);
}
}

Here is a working example. You can enter the required text in the input field and download it as a text file by clicking the download button. A new Blob Object of the MIME type will be created and attaches it to the href of a temporary anchor element and will be triggered programmatically.

--

--

Kayathiri Mahendrakumaran
Frontend Weekly

Senior Software Engineer 👨‍💻, WSO2 | Undergraduate👩‍🎓 , Computer Science & Engineering | Writer ✍️