Skip to content
Components

File Upload

File Upload for a useful, keyboard-friendly product interface.

Open ↗

Make it yours.

Install the editable source and its dependencies into your React + Tailwind project.

Scroll horizontally for long lines
pnpm dlx shadcn@4.0.8 add http://localhost:3000/r/file-upload.json

Use it

Scroll horizontally for long lines
"use client";
import {FileUpload} from '@/components/jez-ui/ui/file-upload';

export default function Example(){

return <><div className="w-full max-w-sm"><div className="mb-7"><h3 className="text-2xl tracking-tight">Bring your ideas.</h3><p className="mt-2 text-sm leading-relaxed text-muted-foreground">Drop in your reference images, sketches, or brief.</p></div><FileUpload accept="image/*,.pdf" multiple/></div></>;
}

Props & types

Scroll horizontally for long lines
{
  accept?: string;
  maxBytes?: number;
  multiple?: boolean;
  onFilesChange?: (files: File[]) => void;
  className?: string;
}

Source

View 3 source files

registry/ui/file-upload.tsx

Scroll horizontally for long lines
"use client";
import * as React from "react";
import { cn } from "./utils";
import { UploadCloud, FileText, X } from "lucide-react";
import { Button } from "./button";
export function FileUpload({
  accept,
  maxBytes = 5 * 1024 * 1024,
  multiple = false,
  onFilesChange,
  className,
}: {
  accept?: string;
  maxBytes?: number;
  multiple?: boolean;
  onFilesChange?: (files: File[]) => void;
  className?: string;
}) {
  const [files, setFiles] = React.useState<File[]>([]);
  const [error, setError] = React.useState("");
  const id = React.useId();
  const [dragging, setDragging] = React.useState(false);
  function choose(list: File[]) {
    const next = multiple ? list : list.slice(0, 1);
    const allowed = (f: File) =>
      !accept ||
      accept.split(",").some((a) => {
        a = a.trim();
        return a.startsWith(".")
          ? f.name.toLowerCase().endsWith(a.toLowerCase())
          : a.endsWith("/*")
            ? f.type.startsWith(a.slice(0, -1))
            : f.type === a;
      });
    if (next.some((f) => f.size > maxBytes)) {
      setError(
        `Each file must be under ${Math.round(maxBytes / 1024 / 1024)} MB.`,
      );
      return;
    }
    if (next.some((f) => !allowed(f))) {
      setError("This file type is not accepted.");
      return;
    }
    setError("");
    setFiles(next);
    onFilesChange?.(next);
  }
  return (
    <div className={cn("grid min-w-0 gap-3", className)}>
      <label
        htmlFor={id}
        onDragOver={(e) => {
          e.preventDefault();
          setDragging(true);
        }}
        onDragLeave={() => setDragging(false)}
        onDrop={(e) => {
          e.preventDefault();
          setDragging(false);
          choose(Array.from(e.dataTransfer.files));
        }}
        className={cn(
          "relative grid min-w-0 cursor-pointer justify-items-center gap-3 rounded-xl border border-dashed border-border bg-muted/20 px-6 py-9 text-center transition-colors hover:border-primary/50 focus-within:ring-2 focus-within:ring-primary",
          dragging && "border-primary bg-primary/5",
        )}
      >
        <span className="mb-1 grid size-11 place-items-center rounded-xl border border-border bg-background shadow-sm">
          <UploadCloud size={20} />
        </span>
        <span className="text-sm font-medium">
          {dragging ? "Drop your files here" : "Drag files here to attach them"}
        </span>
        <span className="text-xs text-muted-foreground">
          Up to {Math.round(maxBytes / 1024 / 1024)} MB per file
        </span>
        <span className="mt-1 rounded-lg border border-border bg-background px-4 py-2 text-sm font-medium shadow-sm">
          Browse files
        </span>
        <input
          id={id}
          aria-label="Choose files"
          type="file"
          accept={accept}
          multiple={multiple}
          onChange={(e) => choose(Array.from(e.target.files ?? []))}
          className="sr-only"
        />
      </label>
      {error && (
        <p role="alert" className="text-sm text-danger">
          {error}
        </p>
      )}
      {files.map((f, i) => (
        <div
          key={f.name + i}
          className="flex items-center gap-3 rounded-lg border border-border p-3 text-sm"
        >
          <FileText className="shrink-0 text-muted-foreground" size={20} />
          <span className="min-w-0 flex-1">
            <span className="block truncate font-medium">{f.name}</span>
            <span className="text-xs text-muted-foreground">
              {f.size < 1024 * 1024
                ? `${Math.max(1, Math.round(f.size / 1024))} KB`
                : `${(f.size / 1024 / 1024).toFixed(1)} MB`}{" "}
              · Attached
            </span>
          </span>
          <Button
            size="sm"
            variant="ghost"
            aria-label={`Remove ${f.name}`}
            onClick={() => {
              const next = files.filter((_, n) => n !== i);
              setFiles(next);
              onFilesChange?.(next);
            }}
          >
            <X size={16} />
          </Button>
        </div>
      ))}
    </div>
  );
}

registry/ui/utils.ts

Scroll horizontally for long lines
import { clsx, type ClassValue } from "clsx";
import { twMerge } from "tailwind-merge";
export function cn(...values: ClassValue[]) {
  return twMerge(clsx(values));
}

registry/ui/button.tsx

Scroll horizontally for long lines
"use client";
import * as React from "react";
import { Slot } from "radix-ui";
import { LoaderCircle } from "lucide-react";
import { cn } from "./utils";
export type ButtonProps = React.ButtonHTMLAttributes<HTMLButtonElement> & {
  variant?: "primary" | "secondary" | "outline" | "ghost" | "danger";
  size?: "sm" | "md" | "lg";
  loading?: boolean;
  asChild?: boolean;
};
export function Button({
  variant = "primary",
  size = "md",
  loading,
  asChild,
  className,
  children,
  disabled,
  ...props
}: ButtonProps) {
  const Comp = asChild ? Slot.Root : "button";
  return (
    <Comp
      type={asChild ? undefined : "button"}
      disabled={asChild ? undefined : disabled || loading}
      aria-disabled={disabled || loading || undefined}
      aria-busy={loading || undefined}
      className={cn(
        "relative inline-flex shrink-0 items-center justify-center gap-2 whitespace-nowrap rounded-lg border border-transparent text-sm font-medium leading-none transition-[background-color,border-color,box-shadow,transform] duration-150 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary active:scale-[.98] disabled:pointer-events-none disabled:opacity-45 aria-disabled:pointer-events-none [&_svg]:shrink-0",
        {
          "bg-primary text-primary-foreground shadow-[inset_0_1px_0_#ffffff26,0_1px_2px_#00000012] hover:bg-primary/90":
            variant === "primary",
          "border-border/60 bg-muted text-foreground hover:bg-muted/70":
            variant === "secondary",
          "border-border bg-background text-foreground shadow-sm hover:bg-muted/60":
            variant === "outline",
          "text-muted-foreground hover:bg-muted hover:text-foreground":
            variant === "ghost",
          "bg-danger text-danger-foreground hover:bg-danger/90":
            variant === "danger",
        },
        {
          "h-8 px-3 text-xs": size === "sm",
          "h-10 px-4": size === "md",
          "h-12 px-6": size === "lg",
        },
        className,
      )}
      {...props}
    >
      {asChild ? (
        children
      ) : (
        <>
          <span
            className={cn(
              "inline-flex min-w-0 flex-1 items-center justify-center gap-2",
              loading && "invisible",
            )}
          >
            {children}
          </span>
          {loading && (
            <LoaderCircle
              aria-hidden="true"
              className="absolute size-4 animate-spin motion-reduce:animate-none"
            />
          )}
        </>
      )}
    </Comp>
  );
}

Dependencies

lucide-react@0.577.0 · clsx@2.1.1 · tailwind-merge@3.5.0 · radix-ui@1.6.7

Accessibility & behaviour

Provide meaningful labels and preserve keyboard focus styles. Check contrast when customising theme colours.

Read the accessibility and performance guide →