When I was building 100 Ideas, I wanted to give users an option to export their content in a text file. It was super simple. This post is an attempt to share that knowledge and log it for the future. Assuming you already know the basics of React, let's begin.
Create a Button
<div className="btnDiv">
<button id="downloadBtn" value="download">Download</button>
</div>
Add Event Handler
const downloadTxtFile = () => {
console.log("download logic goes here")
}
<div className="btnDiv">
<button id="downloadBtn" onClick={downloadTxtFile} value="download">Download</button>
</div>
Next, we need to hook an event handler to the button's onClick
event. Let's do that and see if everything works.
Add Download Logic
To download a file, we need four things.
-
The content that's supposed to go into the file
-
The file object
-
A link to download the file object
-
Finally, simulate that the user clicking the link
const downloadTxtFile = () => { // text content const texts = ["line 1", "line 2", "line 3"] // file object const file = new Blob(texts, {type: 'text/plain'}); // anchor link const element = document.createElement("a"); element.href = URL.createObjectURL(file); element.download = "100ideas-" + Date.now() + ".txt"; // simulate link click document.body.appendChild(element); // Required for this to work in FireFox element.click(); }
Notes
Date.now()
is to add the timestamp to file downloads- The file blob doesn't add a newline to the
texts
automatically. You can use[texts.join('\n')]
to add a new line.
That's it for this topic. Thank you for reading.