DEV Community

Bhavani Ravi
Bhavani Ravi

Posted on • Originally published at thelearning.dev on

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>
Enter fullscreen mode Exit fullscreen mode

Add Event Handler

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

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

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();
}
Enter fullscreen mode Exit fullscreen mode

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

Originally published at https://thelearning.dev.


Top comments (0)