import { Button, DownloadTrigger } from "@chakra-ui/react"
const data = "The quick brown fox jumps over the lazy dog"
const Demo = () => {
return (
<DownloadTrigger
data={data}
fileName="sample.txt"
mimeType="text/plain"
asChild
>
<Button variant="outline">Download txt</Button>
</DownloadTrigger>
)
}
Usage
import { DownloadTrigger } from "@chakra-ui/react"
<DownloadTrigger data="..." fileName="x.png" mimeType="image/png" />
Examples
Basic
Pass the data you want to download to the data
prop, and specify the
fileName
and mimeType
of the file.
import { Button, DownloadTrigger } from "@chakra-ui/react"
const data = "The quick brown fox jumps over the lazy dog"
const Demo = () => {
return (
<DownloadTrigger
data={data}
fileName="sample.txt"
mimeType="text/plain"
asChild
>
<Button variant="outline">Download txt</Button>
</DownloadTrigger>
)
}
Download SVG
Here's an example of how to download an SVG file.
import { Button, DownloadTrigger } from "@chakra-ui/react"
const data = String.raw`
<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100">
<circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red"/>
</svg>
`
const Demo = () => {
return (
<DownloadTrigger
data={data}
fileName="sample.svg"
mimeType="image/svg+xml"
asChild
>
<Button variant="outline">Download svg</Button>
</DownloadTrigger>
)
}
Promise
You can also trigger downloads from a promise that returns a Blob
, File
, or
string
.
"use client"
import { Button, DownloadTrigger } from "@chakra-ui/react"
import { LuImageDown } from "react-icons/lu"
const data = async () => {
const res = await fetch("https://picsum.photos/200/300")
return res.blob()
}
const Demo = () => {
return (
<DownloadTrigger
data={data}
fileName="sample.jpg"
mimeType="image/jpeg"
asChild
>
<Button variant="outline">
<LuImageDown /> Download
</Button>
</DownloadTrigger>
)
}
File Size
Compose the DownloadTrigger
with the FormatByte
component to display the
size of the file in a human-readable format.
import { Button, DownloadTrigger, FormatByte } from "@chakra-ui/react"
import { LuDownload } from "react-icons/lu"
const data = "The quick brown fox jumps over the lazy dog"
const Demo = () => {
return (
<DownloadTrigger
data={data}
fileName="sample.txt"
mimeType="text/plain"
asChild
>
<Button variant="outline">
<LuDownload /> Download (
<FormatByte value={data.length} unitDisplay="narrow" />)
</Button>
</DownloadTrigger>
)
}