---
title: "File Upload · UI SDK — StyleX Blocks"
description: "Dashed dropzone with a file item list showing names, sizes, and delete triggers."
url: "https://stylexblocks.com/components/ui-sdk/file-upload/"
agent:
  instructions: "Use this search API to find relevant components and blocks across this site with keywords or natural-language queries, instead of crawling individual pages. Results are returned in Markdown."
  endpoint: "https://stylexblocks.com/.well-known/search?q={query}"
  method: "GET"
  documentation: "https://developers.cloudflare.com/ai-search/how-to/search-for-agents/"
---

# File Upload

Dashed dropzone with a file item list showing names, sizes, and delete triggers.

- Behavior engine: UI SDK
- Also available for: [Ark UI](https://stylexblocks.com/components/ark-ui/file-upload.md), [Base UI](https://stylexblocks.com/components/base-ui/file-upload.md)
- Category: Form
- HTML page: https://stylexblocks.com/components/ui-sdk/file-upload/

## Install

Configure the project once (sets the behavior engine and import aliases):

```sh
npx stylexblocks init --style ui-sdk
```

Then add the item as source you own:

```sh
npx stylexblocks add file-upload
```

Equivalent: `npx shadcn add @stylexblocks/file-upload`. Registry item JSON: https://stylexblocks.com/r/ui-sdk/file-upload.json

## Usage

```tsx
import { FileUpload } from "#components/ui/ui-sdk/file-upload.tsx";

export function Example() {
  return (
    // UI SDK's FileInput validates and holds the files (accept, maxFiles,
    // maxSize, ...) and submits them with a form via `name`. ItemGroup
    // renders its Item once per file — no mapping — and is one Tab stop:
    // arrows move between files, Delete or Backspace removes one
    <FileUpload.Root maxFiles={5} name="attachments">
      <FileUpload.Label>Attachments</FileUpload.Label>
      <FileUpload.Dropzone>
        <FileUpload.DropzoneContent>
          Drag files here or click to browse
        </FileUpload.DropzoneContent>
      </FileUpload.Dropzone>
      <FileUpload.ItemGroup aria-label="Attachments">
        <FileUpload.Item>
          <FileUpload.ItemContent>
            <FileUpload.ItemName />
            <FileUpload.ItemSizeText />
          </FileUpload.ItemContent>
          <FileUpload.ItemDeleteTrigger />
        </FileUpload.Item>
      </FileUpload.ItemGroup>
    </FileUpload.Root>
  );
}

// file list in code: <FileUpload.Context>{(api) => api.files.length}</FileUpload.Context>
```

## Source

`components/ui/ui-sdk/file-upload.tsx`

```tsx
import * as stylex from "@stylexjs/stylex";
import { createContext, useContext, useState } from "react";
import {
  createFileInputController,
  FileInput as UiSdkFileInput,
  FileInputDropzone,
  FileInputItem,
  FileInputItemRemove,
  FileInputList,
  FileInputTrigger,
  formatFileSize,
  type FileInputController,
  type FileInputState,
} from "@ui-sdk/react/file-input";
import { createSlotRecipeContext } from "#lib/ui-sdk/create-slot-recipe-context.tsx";
import {
  defineSlotRecipe,
  resolveSlotStyles,
  type StyleOverrideProps,
} from "#lib/recipe-props.ts";
import { colorPalette } from '@stylexblocks/ui/color-palette.stylex.ts'
import { durations } from '@stylexblocks/ui/tokens/durations.stylex.ts'
import { fontSizes } from '@stylexblocks/ui/tokens/font-sizes.stylex.ts'
import { fontWeights } from '@stylexblocks/ui/tokens/font-weights.stylex.ts'
import { lineHeights } from '@stylexblocks/ui/tokens/line-heights.stylex.ts'
import { semanticColors } from '@stylexblocks/ui/semantic-tokens/colors.stylex.ts'
import { semanticRadii } from '@stylexblocks/ui/semantic-tokens/radii.stylex.ts'
import { sizes } from '@stylexblocks/ui/tokens/sizes.stylex.ts'
import { spacing } from '@stylexblocks/ui/tokens/spacing.stylex.ts'

const fileUploadRoot = stylex.create({
  base: {
    display: 'flex',
    flexDirection: 'column',
    gap: spacing._4,
    width: '100%',
    alignItems: 'flex-start',
  },
})

const fileUploadLabel = stylex.create({
  base: {
    fontWeight: fontWeights.medium,
    fontSize: fontSizes.sm,
    lineHeight: lineHeights.sm,
  },
})

const fileUploadDropzone = stylex.create({
  base: {
    backgroundColor: semanticColors.bg,
    borderRadius: semanticRadii.panel,
    borderWidth: '1px',
    borderStyle: 'dashed',
    display: 'flex',
    alignItems: 'center',
    flexDirection: 'column',
    gap: spacing._4,
    justifyContent: 'center',
    padding: spacing._4,
    transition: 'backgrounds',
    outlineWidth: {
      default: null,
      ':focus-visible': '1px',
    },
    outlineOffset: {
      default: null,
      ':focus-visible': '2px',
    },
    outlineStyle: {
      default: null,
      ':focus-visible': 'solid',
    },
    outlineColor: {
      default: null,
      ':focus-visible': colorPalette.focusRing,
    },
  },
})

const fileUploadDropzoneContent = stylex.create({
  base: {
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center',
    textAlign: 'center',
    gap: spacing._4,
    fontSize: fontSizes.sm,
    lineHeight: lineHeights.sm,
  },
})

const fileUploadItem = stylex.create({
  base: {
    fontSize: fontSizes.sm,
    lineHeight: lineHeights.sm,
    animationName: 'fade-in',
    animationDuration: durations.moderate,
    backgroundColor: semanticColors.bg,
    borderRadius: semanticRadii.panel,
    borderWidth: '1px',
    width: '100%',
    display: 'flex',
    alignItems: 'center',
    gap: spacing._3,
    paddingInline: spacing._4,
    paddingBlock: spacing._2,
  },
})

const fileUploadItemGroup = stylex.create({
  base: {
    width: '100%',
    display: 'flex',
    flexDirection: 'column',
    gap: spacing._3,
  },
})

const fileUploadItemName = stylex.create({
  base: {
    color: semanticColors.fg,
    fontWeight: fontWeights.medium,
    lineClamp: 1,
  },
})

const fileUploadItemContent = stylex.create({
  base: {
    display: 'flex',
    flexDirection: 'column',
    gap: spacing._0_5,
    flex: 1,
  },
})

const fileUploadItemSizeText = stylex.create({
  base: {
    color: semanticColors.fgMuted,
    fontSize: fontSizes.xs,
    lineHeight: lineHeights.xs,
  },
})

const fileUploadItemDeleteTrigger = stylex.create({
  base: {
    alignSelf: 'flex-start',
  },
})

const fileUploadItemPreviewImage = stylex.create({
  base: {
    width: sizes._10,
    height: sizes._10,
    objectFit: 'scale-down',
  },
})

const fileUploadRecipe = defineSlotRecipe({
  slots: {
    root: { styles: fileUploadRoot },
    label: { styles: fileUploadLabel },
    dropzone: { styles: fileUploadDropzone },
    dropzoneContent: { styles: fileUploadDropzoneContent },
    item: { styles: fileUploadItem },
    itemGroup: { styles: fileUploadItemGroup },
    itemName: { styles: fileUploadItemName },
    itemContent: { styles: fileUploadItemContent },
    itemSizeText: { styles: fileUploadItemSizeText },
    itemDeleteTrigger: { styles: fileUploadItemDeleteTrigger },
    itemPreviewImage: { styles: fileUploadItemPreviewImage },
  },
  defaultVariants: {},
});

// What the recipe leaves to the composition layer: button/list resets, and a
// focus ring for the items — UI SDK makes the file list one Tab stop with
// arrow-key navigation, so items take focus (Ark's don't).
const chrome = stylex.create({
  btnReset: {
    appearance: "none",
    backgroundColor: "transparent",
    borderWidth: 0,
    borderStyle: "none",
    padding: 0,
    margin: 0,
    fontFamily: "inherit",
    fontSize: "inherit",
    color: "inherit",
    cursor: "pointer",
    textAlign: "inherit",
  },
  listReset: { listStyle: "none", margin: 0, padding: 0 },
  itemFocus: {
    outlineWidth: { default: null, ":focus-visible": "2px" },
    outlineStyle: { default: null, ":focus-visible": "solid" },
    outlineOffset: { default: null, ":focus-visible": "1px" },
    outlineColor: { default: null, ":focus-visible": colorPalette.focusRing },
  },
});

function CloseIcon(props: React.ComponentProps<"svg">) {
  return (
    <svg width="16" height="16" viewBox="0 0 16 16" fill="none" aria-hidden="true" {...props}>
      <path d="m4 4 8 8m0-8-8 8" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
    </svg>
  );
}

const ControllerContext = createContext<FileInputController | null>(null);
const StateContext = createContext<FileInputState>({
  value: [],
  disabled: false,
  required: false,
  dragging: false,
});
const ItemContext = createContext<File | null>(null);

const { withProvider, withContext } = createSlotRecipeContext(fileUploadRecipe);

const StyledRoot = withProvider(UiSdkFileInput, "root", "FileUploadRoot");

type UiSdkFileInputProps = React.ComponentProps<typeof UiSdkFileInput>;

export interface FileUploadRootProps
  extends Omit<UiSdkFileInputProps, "style" | "className" | "defaultValue" | "children">,
    StyleOverrideProps {
  /** Prefilled files (maps to UI SDK's `defaultValue`). */
  defaultFiles?: File[];
  /** Runs with the new file list after files are added or removed. */
  onFilesChange?: (files: File[]) => void;
  children?: React.ReactNode;
}

/**
 * FileUpload — dashed dropzone with a file item list, on UI SDK's FileInput:
 * it validates and holds the files (`accept`, `maxFiles`, `maxSize`, ...),
 * renders the hidden input a form submits, announces changes, and makes the
 * list one Tab stop (arrows move, Delete/Backspace removes). Defaults to
 * `multiple`, like the Ark and Base UI versions.
 */
function Root(props: FileUploadRootProps) {
  const {
    defaultFiles,
    onFilesChange,
    onValueChange,
    multiple = true,
    controller: own,
    children,
    ...rest
  } = props;
  const [fallback] = useState(createFileInputController);
  const controller = own ?? fallback;
  return (
    <ControllerContext.Provider value={controller}>
      <StyledRoot
        {...rest}
        multiple={multiple}
        controller={controller}
        defaultValue={defaultFiles}
        onValueChange={(value, details) => {
          onValueChange?.(value, details);
          onFilesChange?.(value);
        }}
      >
        {(state: FileInputState) => (
          <StateContext.Provider value={state}>{children}</StateContext.Provider>
        )}
      </StyledRoot>
    </ControllerContext.Provider>
  );
}
Root.displayName = "FileUploadRoot";

const StyledDropzone = withContext(
  FileInputDropzone,
  (v) => [chrome.btnReset, ...resolveSlotStyles(fileUploadRecipe.slots.dropzone, v)],
  "FileUploadDropzone",
);

/**
 * Takes dropped and pasted files. UI SDK's drop zone is no control, so this
 * one renders a button that opens the picker through the root's controller
 * — one Tab stop, like the Ark and Base UI dropzones.
 */
function Dropzone(
  props: Omit<React.ComponentProps<typeof FileInputDropzone>, "style" | "className"> &
    StyleOverrideProps,
) {
  const controller = useContext(ControllerContext);
  const { onClick, ...rest } = props;
  return (
    <StyledDropzone
      render={<button type="button" />}
      onClick={(event: React.MouseEvent<HTMLDivElement>) => {
        onClick?.(event);
        if (!event.defaultPrevented) controller?.open();
      }}
      {...rest}
    />
  );
}
Dropzone.displayName = "FileUploadDropzone";

const StyledItemGroup = withContext(
  FileInputList,
  (v) => [...resolveSlotStyles(fileUploadRecipe.slots.itemGroup, v), chrome.listReset],
  "FileUploadItemGroup",
);

/**
 * The file list. Its children render once per file, so put a single
 * `FileUpload.Item` template in it — no mapping over the files.
 */
function ItemGroup(
  props: Omit<React.ComponentProps<typeof FileInputList>, "style" | "className"> &
    StyleOverrideProps,
) {
  return <StyledItemGroup render={<ul />} {...props} />;
}
ItemGroup.displayName = "FileUploadItemGroup";

const StyledItem = withContext(
  FileInputItem,
  (v) => [...resolveSlotStyles(fileUploadRecipe.slots.item, v), chrome.itemFocus],
  "FileUploadItem",
);

export interface FileUploadItemProps
  extends Omit<React.ComponentProps<typeof FileInputItem>, "style" | "className" | "children">,
    StyleOverrideProps {
  children?: React.ReactNode;
}

/** One file: the list fills `file` in; pass it to use an item on its own. */
function Item(props: FileUploadItemProps) {
  const { children, ...rest } = props;
  return (
    <StyledItem render={<li />} {...rest}>
      {({ file }: { file: File }) => (
        <ItemContext.Provider value={file}>{children}</ItemContext.Provider>
      )}
    </StyledItem>
  );
}
Item.displayName = "FileUploadItem";

const StyledItemName = withContext("span", "itemName", "FileUploadItemName");

function ItemName(
  props: Omit<React.ComponentProps<typeof StyledItemName>, "children"> & {
    children?: React.ReactNode;
  },
) {
  const file = useContext(ItemContext);
  const { children, ...rest } = props;
  return <StyledItemName {...rest}>{children ?? file?.name}</StyledItemName>;
}
ItemName.displayName = "FileUploadItemName";

const StyledItemSizeText = withContext("span", "itemSizeText", "FileUploadItemSizeText");

function ItemSizeText(
  props: Omit<React.ComponentProps<typeof StyledItemSizeText>, "children"> & {
    children?: React.ReactNode;
  },
) {
  const file = useContext(ItemContext);
  const { children, ...rest } = props;
  return (
    <StyledItemSizeText {...rest}>
      {children ?? (file ? formatFileSize(file.size) : null)}
    </StyledItemSizeText>
  );
}
ItemSizeText.displayName = "FileUploadItemSizeText";

const StyledItemDeleteTrigger = withContext(
  FileInputItemRemove,
  (v) => [chrome.btnReset, ...resolveSlotStyles(fileUploadRecipe.slots.itemDeleteTrigger, v)],
  "FileUploadItemDeleteTrigger",
);

/** Removes its item's file; named "Remove <file name>", out of the Tab order. */
function ItemDeleteTrigger(
  props: Omit<React.ComponentProps<typeof FileInputItemRemove>, "style" | "className"> &
    StyleOverrideProps,
) {
  const { children, ...rest } = props;
  return <StyledItemDeleteTrigger {...rest}>{children ?? <CloseIcon />}</StyledItemDeleteTrigger>;
}
ItemDeleteTrigger.displayName = "FileUploadItemDeleteTrigger";

export interface FileUploadContextValue {
  files: readonly File[];
  disabled: boolean;
  dragging: boolean;
  addFiles: (files: readonly File[] | FileList) => boolean;
  removeFile: (file: File) => boolean;
  clear: () => boolean;
  open: () => boolean;
}

/** Read the file list the way Ark exposes its machine context. */
function Context({
  children,
}: {
  children: (ctx: FileUploadContextValue) => React.ReactNode;
}) {
  const state = useContext(StateContext);
  const controller = useContext(ControllerContext);
  return children({
    files: state.value,
    disabled: state.disabled,
    dragging: state.dragging,
    addFiles: (files) => controller?.addFiles(files) ?? false,
    removeFile: (file) => controller?.removeFile(file) ?? false,
    clear: () => controller?.clear() ?? false,
    open: () => controller?.open() ?? false,
  });
}

export const FileUpload = {
  Root,
  Label: withContext("span", "label", "FileUploadLabel"),
  Dropzone,
  DropzoneContent: withContext("span", "dropzoneContent", "FileUploadDropzoneContent"),
  Trigger: withContext(FileInputTrigger, () => [chrome.btnReset], "FileUploadTrigger"),
  ItemGroup,
  Item,
  ItemContent: withContext("div", "itemContent", "FileUploadItemContent"),
  ItemName,
  ItemSizeText,
  ItemDeleteTrigger,
  Context,
};
```
