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
Top comments (3)
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.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?
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!