|Kit

DownloadButton

A button that saves a file — a Blob, a URL, or what your own fetch resolves to — busy while it loads, silent on success, announced on failure.

DownloadButton saves a file when it is clicked. Give it the file as data: a Blob you already have, a URL, or a function that resolves one of those on click. While a function's promise is pending, the button shows a spinner and ignores further clicks, so a double click saves one file.

The kit never makes a request. Fetching with a token, asking the API for a presigned link or building a CSV happens in your function, which receives an AbortSignal.

import { DownloadButton } from '@42-central/ui-react/download-button';

<DownloadButton
  name="transcript.pdf"
  data={({ signal }) => api.get(`/transcripts/${id}`, { signal }).then((r) => r.blob())}
/>

Playground

Component

Loading preview

Props

Code

<Component size="md" />

A Blob

A Blob (or a File) is saved inside the click, under name. It renders a kit Button and takes its props: variant, color, size, endSlot. The label defaults to "Download" (translations.label), and the leading icon is icons.download.

Code

const notes = new Blob(['Interview notes…'], { type: 'text/plain' });

<DownloadButton data={notes} name="interview-notes.txt" />

A generated CSV

Pass a function to build the file on click rather than on every render. A function may return the Blob directly; nothing waits then.

Code

const toCsv = (rows: string[][]) =>
  new Blob(['\uFEFF', rows.map((row) => row.map(cell).join(',')).join('\n')], {
    type: 'text/csv;charset=utf-8', // the BOM lets Excel read accents
  });

<DownloadButton
  data={() => toCsv(rows)}
  name="grades.csv"
  variant="light"
  color="brand"
  icons={{ download: <FileSpreadsheet className={iconStroke} /> }}
>
  Export CSV
</DownloadButton>

An authenticated fetch

A bare link can't carry a bearer token, so fetch the file yourself and return the Blob. While the promise is pending, the button is busy: a spinner replaces the icon, aria-busy="true" is set, and its name gains "Preparing download…". It stays enabled and keeps focus, so a keyboard user isn't thrown back to the top of the page. Clicks are ignored until the promise settles.

The demo waits 2.5 seconds to stand in for a slow server.

Code

<DownloadButton
  name="transcript.pdf"
  variant="outline"
  data={async ({ signal }) => {
    const response = await fetch(`/api/transcripts/${id}`, {
      headers: { Authorization: `Bearer ${token}` },
      signal,
    });
    if (!response.ok) throw new Error(response.statusText);
    return response.blob();
  }}
>
  Download transcript
</DownloadButton>

Check response.ok: fetch resolves on a 404 too, and its error page would be saved as transcript.pdf.

If the button unmounts before the promise settles (the user navigates away, the dialog closes), signal aborts and nothing is saved afterwards. Pass it on to fetch so the request stops too.

A presigned URL

Return a URL instead of a Blob, and the browser downloads it itself: no memory held, and the browser's own progress UI for a large file. The demo's "API" answers after 0.6 seconds with a file served by this site.

Code

<DownloadButton
  name="grades.csv"
  variant="subtle"
  data={async ({ signal }) => {
    const { url } = await api.get(`/templates/${id}/download`, { signal });
    return url;
  }}
>
  Download the template
</DownloadButton>
Filenames from presigned URLs

Browsers ignore name on a cross-origin URL, such as an S3 presigned link: the download attribute only applies to same-origin, blob: and data: URLs. The file is named by the response's Content-Disposition header, and without attachment the browser opens the file instead of saving it. The fix is on the server: send Content-Disposition: attachment; filename*=UTF-8''<encoded name>. An S3 presign can set it per link with ResponseContentDisposition. This is a request for your backend or API team; the kit won't fetch the file to rename it.

Icon-only, in a row

With asChild, only the behaviour goes onto your element: the click, aria-busy and data-loading, disabled, testId. Use it to make an ActionIcon a download button in a FileItem's actions. Button's styling isn't added, so style the child; while busy, the spinner stands in for its icon.

An icon has no text, so give the child an aria-label that names the file.

  • internship-agreement.pdf
    248 kB Sep 30, 2026
  • transcript-2026.pdf
    1.2 MB Jul 19, 2026

Code

<FileItem
  file={document}
  actions={
    <DownloadButton asChild name={document.name} data={({ signal }) => fetchDocument(document.id, signal)}>
      <ActionIcon variant="subtle" color="neutral" size="xs" aria-label={`Download ${document.name}`}>
        <Download className={iconStroke} aria-hidden />
      </ActionIcon>
    </DownloadButton>
  }
/>

Errors

When the function rejects (or the save throws), the button stops being busy, a polite status region announces "medical-certificate.pdf couldn't be downloaded" (translations.error), and onError receives the error. Nothing is saved, and onDone doesn't fire. The message is cleared on the next click.

Success is silent: the browser's own download bar or panel is the feedback, and an extra announcement would talk over it.

Fails after one second.

Code

<DownloadButton
  name="medical-certificate.pdf"
  data={fetchCertificate}
  onError={(error) => setError(error.message)}
  color="red"
  variant="light"
>
  Download certificate
</DownloadButton>

If onError shows a toast that announces itself, the failure is heard twice. Pass translations={{ error: () => '' }} to leave it to the toast.

Internationalization

Every string the button shows or announces is in translations. An icon-only button's name is your own aria-label.

KeyDefault
label"Download"
loading"Preparing download…"
error(name) => name ? `${name} couldn't be downloaded` : "The download failed"

Code

<DownloadButton
  name="notes.csv"
  data={fetchNotes}
  translations={{
    label: 'Télécharger',
    loading: 'Préparation du téléchargement…',
    error: (name) => (name ? `Échec du téléchargement de ${name}` : 'Échec du téléchargement'),
  }}
/>

The button is a Button, laid out with logical properties: on a right-to-left page the icon moves to the right. The download icon points down, so it isn't mirrored.

Accessibility

  • A real button. It's a <button type="button"> (or your element, under asChild), named by its children or its aria-label. Enter and Space start the download, like a click.
  • Busy, not disabled. While loading it keeps focus and stays in the tab order, with aria-busy="true" and "Preparing download…" added to its name. Button's own loading sets disabled, which would drop focus to the page, so DownloadButton doesn't use it.
  • One announcement, on failure. A role="status" region beside the button speaks only when the download fails. It's visually hidden with position: fixed, so it can't stretch a scrolling container.
  • Disabled disables the button; under asChild the child gets disabled and aria-disabled, and a click saves nothing.

Slow downloads and Safari

A save that follows a long await is no longer part of the click: the page's transient user activation, which lets a script do what only a click may, lapses a few seconds after it (five in Chrome; WebKit had dropped it by six in our run). Browsers block a popup opened that late. A download through a link with a download attribute, which is how DownloadButton saves, isn't gated on activation.

We checked it in Chromium and WebKit, the engine behind Safari, through Playwright. A Blob saved six seconds after the click, when navigator.userActivation.isActive had already turned false, still downloaded in both, with the right name and bytes. So did the demos above: a Blob, a promise after 2.5 seconds, and a same-origin URL. A cross-origin URL returned after 2.5 seconds downloaded too, named by its Content-Disposition, and the page stayed put.

What headless WebKit can't show is the Safari app's own "Do you want to allow downloads on this site?" prompt, which it asks once per site. If a user declines it, nothing is saved and nothing fails in the page, so onDone still fires.

saveFile

The function underneath, exported from the package root for code that isn't a button: a menu item, a keyboard shortcut, the end of a form submission. See File helpers.

import { saveFile } from '@42-central/ui-react';

saveFile(blob, 'grades.csv');

API

Prop

Type

A caller's onClick runs first: call event.preventDefault() in it to stop the save (a confirmation step). endSlot and the other Button props pass through; loading and startSlot don't exist here, since the button manages its own busy state and icon.

Changelog

v0.20.0
  • New DownloadButton: data is a Blob, a URL or ({ signal }) => Promise<Blob | string>; it keeps focus with a spinner while pending, ignores repeat clicks, announces failures, and takes onDone/onError/asChild. saveFile(data, name) does it without a button

    #368

On this page