How to Create a Download Button Using React
A guide on creating a download button using React.
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
💡 Note: If you’re facing re-rending issues in your React project, useState in your custom hooks might be the reason. Learn more here:
👉 Learn to improve your React app’s performance using the intersection observer API:
Originally published at https://thelearning.dev.
In Plain English 🚀
Thank you for being a part of the In Plain English community! Before you go:
- Be sure to clap and follow the writer ️👏️️
- Follow us: X | LinkedIn | YouTube | Discord | Newsletter
- Visit our other platforms: CoFeed | Differ
- More content at PlainEnglish.io