DEV Community

Josh Ellis
Josh Ellis

Posted on

Simple Download Text File Component with React

I'm working on a project with a feature where you can save a text file after you've created a list. Creating a component that saves a text file is a lot simpler than I expected it to be!

This is the component I came up with...

import React, { useEffect, useState } from 'react'

export const SaveList: React.FC = ({list}) => {
  // set up local state for generating the download link
  const [downloadLink, setDownloadLink] = useState('')

  // function for generating file and set download link
  const makeTextFile = () => {
    // This creates the file. 
    // In my case, I have an array, and each item in 
    // the array should be on a new line, which is why
    // I use .join('\n') here.
    const data = new Blob([list.join('\n')], { type: 'text/plain' })

    // this part avoids memory leaks
    if (downloadLink !== '') window.URL.revokeObjectURL(downloadLink)

    // update the download link state
    setDownloadLink(window.URL.createObjectURL(data))
  }

  // Call the function if list changes
  useEffect(() => {
    makeTextFile()
  }, [list])

  return (
    <a
      // this attribute sets the filename
      download='list.txt'
      // link to the download URL
      href={downloadLink}
    >
      download
    </a>
  )
}

export default SaveList
Enter fullscreen mode Exit fullscreen mode

Top comments (3)

Collapse
 
bazmatic profile image
Barry Earsman

Thanks, I found this useful! Actually, you could make this even simpler. There's no need to use useEffect or have any state variables if the process of creating the link is synchronous.

export const SaveList: React.ReactElement = ({list}) => {
    const data = new Blob([list.join('\n')], { type: 'text/plain' })
    const downloadLink = window.URL.createObjectURL(data)
    return (
      <>
        <a download='list.txt' href={downloadLink}>download</a>
      </>
    );
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
kawanofer profile image
Fernando Kawano

Hi! This post helped me a lot, thanks! Do you know if it there's is a way to download and save the file without user action?

Collapse
 
imjoshellis profile image
Josh Ellis

Haven’t done it myself, so I can’t help you any more than Google would, but I’m sure there’s a straightforward way to trigger a download automatically since so many sites do it!