Created
February 14, 2023 07:46
-
-
Save tomfa/b8f8ccbafb24ab22fdda4e4d8c9fc20a to your computer and use it in GitHub Desktop.
React hook for downloading csv files (typescript)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useCallback } from 'react'; | |
export function useCsvDownload( | |
data: Record<string, any>[], | |
title = 'data.csv', | |
) { | |
return useCallback(() => { | |
const headerKeys = data | |
.map((d) => Object.keys(d)) | |
.reduce((a, b) => { | |
b.forEach((item) => a.add(item)); | |
return a; | |
}, new Set<string>()); | |
const headers = Array.from(headerKeys).join(';'); | |
const rows = data | |
.map((d) => | |
Object.values(d) | |
.map((v) => `"${v}"`) | |
.join(';'), | |
) | |
.join('\n'); | |
const csvContent = `data:text/csv;charset=utf-8,${headers}\n${rows}`; | |
const uriData = encodeURI(csvContent); | |
const link = document.createElement('a'); | |
link.href = uriData; | |
link.download = title; | |
document.body.appendChild(link); | |
link.click(); | |
document.body.removeChild(link); | |
}, [data, title]); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment