How to Create a Download Button Using React

A guide on creating a download button using React.

Bhavani Ravi
JavaScript in Plain English
2 min readJun 2, 2022

--

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.

  1. The content that's supposed to go into the file
  2. The file object
  3. A link to download the file object
  4. 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

  1. Date.now() is to add the timestamp to file downloads
  2. 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:

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Published in JavaScript in Plain English

New JavaScript and Web Development content every day. Follow to join our 3.5M+ monthly readers.

Written by Bhavani Ravi

🔸 Backend Systems & Devops🔸 Code — Speak — Write — Teach 🔸 Python — Data — DevOps | Apache Airflow 🔸 WomenInTech 🔸

Responses (1)

What are your thoughts?