How to create a file downloader in React

Downloading files programmatically is a common requirement in modern web applications, from exporting reports to downloading generated content. As the creator of CoreUI, a widely used open-source UI library with extensive React support, I’ve implemented file download functionality countless times over my 11 years of React development. The most reliable approach is creating a temporary object URL from a Blob and triggering a download via a programmatic anchor click. This method works consistently across all modern browsers and gives you full control over the download process.

Create a Blob from your data, generate an object URL, and trigger a download using a temporary anchor element.

const DownloadButton = () => {
  const handleDownload = () => {
    const data = 'This is the file content'
    const blob = new Blob([data], { type: 'text/plain' })
    const url = URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = 'example.txt'
    link.click()
    URL.revokeObjectURL(url)
  }

  return <button onClick={handleDownload}>Download File</button>
}

Here a Blob is created from the file content with the appropriate MIME type. The URL.createObjectURL() method generates a temporary URL pointing to the Blob. A hidden anchor element is created programmatically with the download attribute set to the desired filename. Calling click() triggers the browser’s download mechanism. Finally, URL.revokeObjectURL() releases the memory used by the object URL.

Best Practice Note:

This is the same approach we use in CoreUI components for exporting data and generating downloadable reports. Always revoke object URLs after use to prevent memory leaks, especially in single-page applications where components mount and unmount frequently.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author