TheLearningDev's Blog

TheLearningDev's Blog

How to Download Files on Button Click ReactJS?

Bhavani Ravi's photo
Bhavani Ravi
ยทMay 31, 2022ยท

2 min read

Subscribe to our newsletter and never miss any upcoming articles

Table of contents

  • Create a Button
  • Add Event Handler
  • Add Download Logic

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

Next, we need to hook an event handler to the button'sonClick event. Let's do that and see if everything works.

const downloadTxtFile = () => {
    console.log("download logic goes here")
}

<div className="btnDiv">
     <button id="downloadBtn" onClick={downloadTxtFile} value="download">Download</button>
</div>

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 new line
ย 
Share this