Attachment Field
A component where you can select files or upload via drag and drop.
import { VStack } from "@seed-design/react";
import { AttachmentField, AttachmentInput } from "seed-design/ui/attachment-field";
export default function AttachmentFieldPreview() {
return (
<VStack gap="x4" p="x6" width="100%">
<AttachmentField
maxFiles={3}
label="파일 업로드"
description="최대 3개까지 업로드할 수 있습니다"
>
<AttachmentInput />
</AttachmentField>
</VStack>
);
}Installation
Default
Includes components that can be used when reordering files is not needed.
npx @seed-design/cli@latest add ui:attachment-fieldpnpm dlx @seed-design/cli@latest add ui:attachment-fieldyarn dlx @seed-design/cli@latest add ui:attachment-fieldbun x @seed-design/cli@latest add ui:attachment-fieldInstall dependencies
npm install @karrotmarket/react-monochrome-icon @seed-design/css @seed-design/reactyarn add @karrotmarket/react-monochrome-icon @seed-design/css @seed-design/reactpnpm add @karrotmarket/react-monochrome-icon @seed-design/css @seed-design/reactbun add @karrotmarket/react-monochrome-icon @seed-design/css @seed-design/reactCopy the code below and paste it in
/**
* @file ui:attachment-field
* @requires @seed-design/react@^2.0.0
* @requires @seed-design/css@^2.0.0
**/
"use client";
import * as React from "react";
import {
Field as SeedField,
AttachmentInput as SeedAttachmentInput,
Icon,
PrefixIcon,
VisuallyHidden,
} from "@seed-design/react";
import {
useFileUploadContext,
type FileEntry,
type UseFileUploadReturn,
} from "@seed-design/react/primitive";
import type { FieldLabelVariantProps } from "@seed-design/css/recipes/field-label";
import {
IconCameraFill,
IconPaperclipFill,
IconExclamationmarkCircleFill,
IconArrowUpBracketDownFill,
IconArrowClockwiseCircularFill,
IconXmarkFill,
} from "@karrotmarket/react-monochrome-icon";
import { ActionButton } from "./action-button";
import { ProgressCircle } from "./progress-circle";
import { formatBytes } from "../lib/format-bytes";
// You may implement your own i18n for these labels
const LABEL_SELECT_FILE = "파일 선택";
const LABEL_DROP_FILE = "또는 여기로 드래그해서 업로드";
const LABEL_RETRY = "재시도";
const LABEL_REMOVE_FILE = "파일 제거";
export interface AttachmentFieldProps extends Omit<SeedAttachmentInput.RootProps, "asChild"> {
label?: React.ReactNode;
/**
* @default "medium"
*/
labelWeight?: FieldLabelVariantProps["weight"];
indicator?: React.ReactNode;
description?: React.ReactNode;
errorMessage?: React.ReactNode;
showRequiredIndicator?: boolean;
inputProps?: React.InputHTMLAttributes<HTMLInputElement>;
fieldRef?: React.Ref<HTMLDivElement>;
rootProps?: React.HTMLAttributes<HTMLDivElement>;
}
/**
* @see https://crispy.carrot-soft.tech/react/components/attachment-field
*/
export const AttachmentField = React.forwardRef<HTMLInputElement, AttachmentFieldProps>(
(
{
label,
labelWeight,
indicator,
description,
errorMessage,
showRequiredIndicator,
children,
inputProps,
fieldRef,
rootProps,
...props
},
ref,
) => {
const renderHeader = label || indicator;
const renderDescription = !!description;
const renderErrorMessage = errorMessage && props.invalid;
const renderFooter = renderDescription || renderErrorMessage;
if (process.env.NODE_ENV !== "production" && !label) {
console.warn(
"AttachmentField: Provide a `label` prop for better accessibility. This warning will not be shown in production builds.",
);
}
return (
<SeedField.Root
{...rootProps}
name={props.name}
disabled={props.disabled}
required={props.required}
invalid={props.invalid}
readOnly={props.readOnly}
ref={fieldRef}
>
{renderHeader && (
<SeedField.Header>
<SeedField.Label weight={labelWeight}>
{label}
{showRequiredIndicator && <SeedField.RequiredIndicator />}
{indicator && <SeedField.IndicatorText>{indicator}</SeedField.IndicatorText>}
</SeedField.Label>
{/* You might want to put your custom element here */}
</SeedField.Header>
)}
<SeedAttachmentInput.Root {...props}>
{children}
<SeedAttachmentInput.HiddenInput ref={ref} {...inputProps} />
</SeedAttachmentInput.Root>
{renderFooter && (
<SeedField.Footer>
{renderDescription &&
(renderErrorMessage ? (
<VisuallyHidden asChild>
<SeedField.Description>{description}</SeedField.Description>
</VisuallyHidden>
) : (
<SeedField.Description>{description}</SeedField.Description>
))}
{renderErrorMessage && (
<SeedField.ErrorMessage>
<PrefixIcon svg={<IconExclamationmarkCircleFill />} />
{errorMessage}
</SeedField.ErrorMessage>
)}
</SeedField.Footer>
)}
</SeedField.Root>
);
},
);
AttachmentField.displayName = "AttachmentField";
export type AttachmentInputProps =
| { children: SeedAttachmentInput.ContextProps["children"]; onRetry?: never }
| {
children?: undefined;
onRetry?: (
fileEntry: FileEntry,
helpers: Pick<UseFileUploadReturn, "updateFileEntryStatus">,
) => void;
};
export const AttachmentInput = React.forwardRef<HTMLDivElement, AttachmentInputProps>(
({ children, onRetry }, ref) => {
return (
<SeedAttachmentInput.Container ref={ref}>
<SeedAttachmentInput.Trigger aria-label={LABEL_SELECT_FILE}>
<SeedAttachmentInput.TriggerIcon
image={<IconCameraFill />}
general={<IconPaperclipFill />}
/>
<SeedAttachmentInput.TriggerItemCount />
</SeedAttachmentInput.Trigger>
<SeedAttachmentInput.ItemGroup>
<SeedAttachmentInput.Context>
{typeof children === "function"
? children
: ({ acceptedFileEntries, updateFileEntryStatus }) =>
acceptedFileEntries.map((fileEntry) => (
<AttachmentInputItem
key={fileEntry.id}
fileEntry={fileEntry}
{...(onRetry && {
onRetry: () => onRetry(fileEntry, { updateFileEntryStatus }),
})}
/>
))}
</SeedAttachmentInput.Context>
</SeedAttachmentInput.ItemGroup>
</SeedAttachmentInput.Container>
);
},
);
AttachmentInput.displayName = "AttachmentInput";
export type AttachmentDropzoneProps =
| { children: SeedAttachmentInput.ContextProps["children"]; onRetry?: never }
| {
children?: undefined;
onRetry?: (
fileEntry: FileEntry,
helpers: Pick<UseFileUploadReturn, "updateFileEntryStatus">,
) => void;
};
export const AttachmentDropzone: React.FC<AttachmentDropzoneProps> = ({ children, onRetry }) => {
const { triggerProps } = useFileUploadContext();
return (
<>
<SeedAttachmentInput.Dropzone>
<ActionButton variant="neutralWeak" size="small" layout="withText" {...triggerProps}>
<PrefixIcon svg={<IconArrowUpBracketDownFill />} />
{LABEL_SELECT_FILE}
</ActionButton>
<SeedAttachmentInput.DropzoneLabel>{LABEL_DROP_FILE}</SeedAttachmentInput.DropzoneLabel>
</SeedAttachmentInput.Dropzone>
<SeedAttachmentInput.Container>
<SeedAttachmentInput.ItemGroup>
<SeedAttachmentInput.Context>
{typeof children === "function"
? children
: ({ acceptedFileEntries, updateFileEntryStatus }) =>
acceptedFileEntries.map((fileEntry) => (
<AttachmentInputItem
key={fileEntry.id}
fileEntry={fileEntry}
{...(onRetry && {
onRetry: () => onRetry(fileEntry, { updateFileEntryStatus }),
})}
/>
))}
</SeedAttachmentInput.Context>
</SeedAttachmentInput.ItemGroup>
</SeedAttachmentInput.Container>
</>
);
};
AttachmentDropzone.displayName = "AttachmentDropzone";
export interface AttachmentInputItemProps extends Omit<SeedAttachmentInput.ItemProps, "children"> {
onRetry?: () => void;
}
/**
* @see https://crispy.carrot-soft.tech/react/components/attachment-field
*/
export const AttachmentInputItem = React.forwardRef<HTMLLIElement, AttachmentInputItemProps>(
({ onRetry, ...props }, ref) => {
const { acceptType } = useFileUploadContext();
return (
<SeedAttachmentInput.Item ref={ref} {...props}>
<SeedAttachmentInput.ItemImage />
<SeedAttachmentInput.ItemThumbnail>
<Icon svg={<IconPaperclipFill />} />
</SeedAttachmentInput.ItemThumbnail>
<SeedAttachmentInput.ItemMetadata>
<SeedAttachmentInput.ItemName />
<SeedAttachmentInput.ItemSize formatBytes={formatBytes} />
</SeedAttachmentInput.ItemMetadata>
<SeedAttachmentInput.ItemBackdrop status="uploading">
{(entry) => (
<ProgressCircle
size="24"
tone={acceptType === "image" ? "staticWhite" : "neutral"}
{...("progress" in entry && { value: entry.progress })}
/>
)}
</SeedAttachmentInput.ItemBackdrop>
{onRetry && (
<SeedAttachmentInput.ItemBackdrop status="error">
<SeedAttachmentInput.ItemActionButton onClick={onRetry}>
<Icon svg={<IconArrowClockwiseCircularFill />} />
{LABEL_RETRY}
</SeedAttachmentInput.ItemActionButton>
</SeedAttachmentInput.ItemBackdrop>
)}
<SeedAttachmentInput.ItemRemoveButton aria-label={LABEL_REMOVE_FILE}>
<Icon svg={<IconXmarkFill />} />
</SeedAttachmentInput.ItemRemoveButton>
</SeedAttachmentInput.Item>
);
},
);
AttachmentInputItem.displayName = "AttachmentInputItem";
/**
* This file is a snippet from Crispy, helping you get started quickly with @seed-design/* packages.
* You can extend this snippet however you want.
*/
Reorderable
Includes components that can be used when reordering files via drag and drop is needed. The dnd-kit dependency is added to the project.
npx @seed-design/cli@latest add ui:attachment-field-reorderablepnpm dlx @seed-design/cli@latest add ui:attachment-field-reorderableyarn dlx @seed-design/cli@latest add ui:attachment-field-reorderablebun x @seed-design/cli@latest add ui:attachment-field-reorderableInstall dependencies
npm install @dnd-kit/abstract @dnd-kit/dom @dnd-kit/react @karrotmarket/react-monochrome-icon @seed-design/css @seed-design/reactyarn add @dnd-kit/abstract @dnd-kit/dom @dnd-kit/react @karrotmarket/react-monochrome-icon @seed-design/css @seed-design/reactpnpm add @dnd-kit/abstract @dnd-kit/dom @dnd-kit/react @karrotmarket/react-monochrome-icon @seed-design/css @seed-design/reactbun add @dnd-kit/abstract @dnd-kit/dom @dnd-kit/react @karrotmarket/react-monochrome-icon @seed-design/css @seed-design/reactCopy the code below and paste it in
/**
* @file ui:attachment-field-reorderable
* @requires @seed-design/react@^2.0.0
* @requires @seed-design/css@^2.0.0
**/
"use client";
import * as React from "react";
import {
Field as SeedField,
AttachmentInput as SeedAttachmentInput,
Icon,
PrefixIcon,
VisuallyHidden,
} from "@seed-design/react";
import {
useFileUploadContext,
type FileEntry,
type UseFileUploadReturn,
} from "@seed-design/react/primitive";
import type { FieldLabelVariantProps } from "@seed-design/css/recipes/field-label";
import {
IconCameraFill,
IconPaperclipFill,
IconExclamationmarkCircleFill,
IconArrowUpBracketDownFill,
IconArrowClockwiseCircularFill,
IconXmarkFill,
} from "@karrotmarket/react-monochrome-icon";
import { ActionButton } from "./action-button";
import { ProgressCircle } from "./progress-circle";
import { formatBytes } from "../lib/format-bytes";
// You may implement your own i18n for these labels
const LABEL_SELECT_FILE = "파일 선택";
const LABEL_DROP_FILE = "또는 여기로 드래그해서 업로드";
const LABEL_RETRY = "재시도";
const LABEL_REMOVE_FILE = "파일 제거";
export interface AttachmentFieldProps extends Omit<SeedAttachmentInput.RootProps, "asChild"> {
label?: React.ReactNode;
/**
* @default "medium"
*/
labelWeight?: FieldLabelVariantProps["weight"];
indicator?: React.ReactNode;
description?: React.ReactNode;
errorMessage?: React.ReactNode;
showRequiredIndicator?: boolean;
inputProps?: React.InputHTMLAttributes<HTMLInputElement>;
fieldRef?: React.Ref<HTMLDivElement>;
rootProps?: React.HTMLAttributes<HTMLDivElement>;
}
/**
* @see https://crispy.carrot-soft.tech/react/components/attachment-field
*/
export const AttachmentField = React.forwardRef<HTMLInputElement, AttachmentFieldProps>(
(
{
label,
labelWeight,
indicator,
description,
errorMessage,
showRequiredIndicator,
children,
inputProps,
fieldRef,
rootProps,
...props
},
ref,
) => {
const renderHeader = label || indicator;
const renderDescription = !!description;
const renderErrorMessage = errorMessage && props.invalid;
const renderFooter = renderDescription || renderErrorMessage;
if (process.env.NODE_ENV !== "production" && !label) {
console.warn(
"AttachmentField: Provide a `label` prop for better accessibility. This warning will not be shown in production builds.",
);
}
return (
<SeedField.Root
{...rootProps}
name={props.name}
disabled={props.disabled}
required={props.required}
invalid={props.invalid}
readOnly={props.readOnly}
ref={fieldRef}
>
{renderHeader && (
<SeedField.Header>
<SeedField.Label weight={labelWeight}>
{label}
{showRequiredIndicator && <SeedField.RequiredIndicator />}
{indicator && <SeedField.IndicatorText>{indicator}</SeedField.IndicatorText>}
</SeedField.Label>
{/* You might want to put your custom element here */}
</SeedField.Header>
)}
<SeedAttachmentInput.Root {...props}>
{children}
<SeedAttachmentInput.HiddenInput ref={ref} {...inputProps} />
</SeedAttachmentInput.Root>
{renderFooter && (
<SeedField.Footer>
{renderDescription &&
(renderErrorMessage ? (
<VisuallyHidden asChild>
<SeedField.Description>{description}</SeedField.Description>
</VisuallyHidden>
) : (
<SeedField.Description>{description}</SeedField.Description>
))}
{renderErrorMessage && (
<SeedField.ErrorMessage>
<PrefixIcon svg={<IconExclamationmarkCircleFill />} />
{errorMessage}
</SeedField.ErrorMessage>
)}
</SeedField.Footer>
)}
</SeedField.Root>
);
},
);
AttachmentField.displayName = "AttachmentField";
export type AttachmentInputProps =
| { children: SeedAttachmentInput.ContextProps["children"]; onRetry?: never }
| {
children?: undefined;
onRetry?: (
fileEntry: FileEntry,
helpers: Pick<UseFileUploadReturn, "updateFileEntryStatus">,
) => void;
};
export const AttachmentInput = React.forwardRef<HTMLDivElement, AttachmentInputProps>(
({ children, onRetry }, ref) => {
return (
<SeedAttachmentInput.Container ref={ref}>
<SeedAttachmentInput.Trigger aria-label={LABEL_SELECT_FILE}>
<SeedAttachmentInput.TriggerIcon
image={<IconCameraFill />}
general={<IconPaperclipFill />}
/>
<SeedAttachmentInput.TriggerItemCount />
</SeedAttachmentInput.Trigger>
<SeedAttachmentInput.ItemGroup>
<SeedAttachmentInput.Context>
{typeof children === "function"
? children
: ({ acceptedFileEntries, updateFileEntryStatus }) =>
acceptedFileEntries.map((fileEntry) => (
<AttachmentInputItem
key={fileEntry.id}
fileEntry={fileEntry}
{...(onRetry && {
onRetry: () => onRetry(fileEntry, { updateFileEntryStatus }),
})}
/>
))}
</SeedAttachmentInput.Context>
</SeedAttachmentInput.ItemGroup>
</SeedAttachmentInput.Container>
);
},
);
AttachmentInput.displayName = "AttachmentInput";
export type AttachmentDropzoneProps =
| { children: SeedAttachmentInput.ContextProps["children"]; onRetry?: never }
| {
children?: undefined;
onRetry?: (
fileEntry: FileEntry,
helpers: Pick<UseFileUploadReturn, "updateFileEntryStatus">,
) => void;
};
export const AttachmentDropzone: React.FC<AttachmentDropzoneProps> = ({ children, onRetry }) => {
const { triggerProps } = useFileUploadContext();
return (
<>
<SeedAttachmentInput.Dropzone>
<ActionButton variant="neutralWeak" size="small" layout="withText" {...triggerProps}>
<PrefixIcon svg={<IconArrowUpBracketDownFill />} />
{LABEL_SELECT_FILE}
</ActionButton>
<SeedAttachmentInput.DropzoneLabel>{LABEL_DROP_FILE}</SeedAttachmentInput.DropzoneLabel>
</SeedAttachmentInput.Dropzone>
<SeedAttachmentInput.Container>
<SeedAttachmentInput.ItemGroup>
<SeedAttachmentInput.Context>
{typeof children === "function"
? children
: ({ acceptedFileEntries, updateFileEntryStatus }) =>
acceptedFileEntries.map((fileEntry) => (
<AttachmentInputItem
key={fileEntry.id}
fileEntry={fileEntry}
{...(onRetry && {
onRetry: () => onRetry(fileEntry, { updateFileEntryStatus }),
})}
/>
))}
</SeedAttachmentInput.Context>
</SeedAttachmentInput.ItemGroup>
</SeedAttachmentInput.Container>
</>
);
};
AttachmentDropzone.displayName = "AttachmentDropzone";
export interface AttachmentInputItemProps extends Omit<SeedAttachmentInput.ItemProps, "children"> {
onRetry?: () => void;
}
/**
* @see https://crispy.carrot-soft.tech/react/components/attachment-field
*/
export const AttachmentInputItem = React.forwardRef<HTMLLIElement, AttachmentInputItemProps>(
({ onRetry, ...props }, ref) => {
const { acceptType } = useFileUploadContext();
return (
<SeedAttachmentInput.Item ref={ref} {...props}>
<SeedAttachmentInput.ItemImage />
<SeedAttachmentInput.ItemThumbnail>
<Icon svg={<IconPaperclipFill />} />
</SeedAttachmentInput.ItemThumbnail>
<SeedAttachmentInput.ItemMetadata>
<SeedAttachmentInput.ItemName />
<SeedAttachmentInput.ItemSize formatBytes={formatBytes} />
</SeedAttachmentInput.ItemMetadata>
<SeedAttachmentInput.ItemBackdrop status="uploading">
{(entry) => (
<ProgressCircle
size="24"
tone={acceptType === "image" ? "staticWhite" : "neutral"}
{...("progress" in entry && { value: entry.progress })}
/>
)}
</SeedAttachmentInput.ItemBackdrop>
{onRetry && (
<SeedAttachmentInput.ItemBackdrop status="error">
<SeedAttachmentInput.ItemActionButton onClick={onRetry}>
<Icon svg={<IconArrowClockwiseCircularFill />} />
{LABEL_RETRY}
</SeedAttachmentInput.ItemActionButton>
</SeedAttachmentInput.ItemBackdrop>
)}
<SeedAttachmentInput.ItemRemoveButton aria-label={LABEL_REMOVE_FILE}>
<Icon svg={<IconXmarkFill />} />
</SeedAttachmentInput.ItemRemoveButton>
</SeedAttachmentInput.Item>
);
},
);
AttachmentInputItem.displayName = "AttachmentInputItem";
/**
* This file is a snippet from Crispy, helping you get started quickly with @seed-design/* packages.
* You can extend this snippet however you want.
*/
/**
* @file ui:attachment-field-reorderable
* @requires @seed-design/react@^2.0.0
* @requires @seed-design/css@^2.0.0
* @requires @dnd-kit/react@^0.4.0
* @requires @dnd-kit/abstract@^0.4.0
* @requires @dnd-kit/dom@^0.4.0
**/
"use client";
import * as React from "react";
import { AttachmentInput as SeedAttachmentInput, PrefixIcon } from "@seed-design/react";
import {
useFileUploadContext,
type FileEntry,
type UseFileUploadReturn,
} from "@seed-design/react/primitive";
import {
IconCameraFill,
IconPaperclipFill,
IconArrowUpBracketDownFill,
} from "@karrotmarket/react-monochrome-icon";
import { ActionButton } from "./action-button";
import { AttachmentInputItem, type AttachmentInputItemProps } from "./attachment-field";
import { DragDropProvider } from "@dnd-kit/react";
import { isSortable, useSortable } from "@dnd-kit/react/sortable";
import { RestrictToHorizontalAxis } from "@dnd-kit/abstract/modifiers";
import { Accessibility, AutoScroller } from "@dnd-kit/dom";
const LABEL_SELECT_FILE = "파일 선택";
const LABEL_DROP_FILE = "또는 여기로 드래그해서 업로드";
const autoScrollerPlugin = AutoScroller.configure({ threshold: { x: 0.2, y: 0 } });
const accessibilityPlugin = Accessibility.configure({
screenReaderInstructions: {
draggable:
"항목을 집어 항목 순서 변경을 시작하려면 스페이스 바를 누르세요. 방향키를 사용하여 순서를 변경한 뒤 스페이스 바를 다시 눌러 순서 변경을 종료하거나 Esc 키로 순서 변경을 취소할 수 있어요.",
},
announcements: {
dragstart: ({ operation: { source } }) => {
if (!source) return;
return `${source.data.name} 항목 순서 변경을 시작했어요.`;
},
dragend: ({ operation: { source }, canceled }) => {
if (!source || !isSortable(source)) return;
if (canceled) return `${source.data.name} 항목 순서 변경을 취소했어요.`;
return `${source.data.name} 항목을 ${source.sortable.index + 1}번째에 놓았어요.`;
},
},
} satisfies NonNullable<ConstructorParameters<typeof Accessibility>[1]>);
export type AttachmentInputReorderableProps =
| { children: SeedAttachmentInput.ContextProps["children"]; onRetry?: never }
| {
children?: undefined;
onRetry?: (
fileEntry: FileEntry,
helpers: Pick<UseFileUploadReturn, "updateFileEntryStatus">,
) => void;
};
export const AttachmentInputReorderable = React.forwardRef<
HTMLDivElement,
AttachmentInputReorderableProps
>(({ children, onRetry }, ref) => {
const { reorderFileEntry } = useFileUploadContext();
return (
<DragDropProvider
plugins={(defaults) => [...defaults, autoScrollerPlugin, accessibilityPlugin]}
onDragEnd={({ canceled, operation: { source } }) => {
if (canceled) return;
if (!isSortable(source)) return;
reorderFileEntry(source.sortable.initialIndex, source.sortable.index);
}}
>
<SeedAttachmentInput.Container ref={ref}>
<SeedAttachmentInput.Trigger aria-label={LABEL_SELECT_FILE}>
<SeedAttachmentInput.TriggerIcon
image={<IconCameraFill />}
general={<IconPaperclipFill />}
/>
<SeedAttachmentInput.TriggerItemCount />
</SeedAttachmentInput.Trigger>
<SeedAttachmentInput.ItemGroup>
<SeedAttachmentInput.Context>
{typeof children === "function"
? children
: ({ acceptedFileEntries, updateFileEntryStatus }) =>
acceptedFileEntries.map((fileEntry, index) => (
<SortableAttachmentInputItem
key={fileEntry.id}
fileEntry={fileEntry}
index={index}
{...(onRetry && {
onRetry: () => onRetry(fileEntry, { updateFileEntryStatus }),
})}
/>
))}
</SeedAttachmentInput.Context>
</SeedAttachmentInput.ItemGroup>
</SeedAttachmentInput.Container>
</DragDropProvider>
);
});
AttachmentInputReorderable.displayName = "AttachmentInputReorderable";
export type AttachmentDropzoneReorderableProps =
| { children: SeedAttachmentInput.ContextProps["children"]; onRetry?: never }
| {
children?: undefined;
onRetry?: (
fileEntry: FileEntry,
helpers: Pick<UseFileUploadReturn, "updateFileEntryStatus">,
) => void;
};
export const AttachmentDropzoneReorderable: React.FC<AttachmentDropzoneReorderableProps> = ({
children,
onRetry,
}) => {
const { triggerProps, reorderFileEntry } = useFileUploadContext();
return (
<>
<SeedAttachmentInput.Dropzone>
<ActionButton variant="neutralWeak" size="small" layout="withText" {...triggerProps}>
<PrefixIcon svg={<IconArrowUpBracketDownFill />} />
{LABEL_SELECT_FILE}
</ActionButton>
<SeedAttachmentInput.DropzoneLabel>{LABEL_DROP_FILE}</SeedAttachmentInput.DropzoneLabel>
</SeedAttachmentInput.Dropzone>
<DragDropProvider
plugins={(defaults) => [...defaults, autoScrollerPlugin, accessibilityPlugin]}
onDragEnd={({ canceled, operation: { source } }) => {
if (canceled) return;
if (!isSortable(source)) return;
reorderFileEntry(source.sortable.initialIndex, source.sortable.index);
}}
>
<SeedAttachmentInput.Container>
<SeedAttachmentInput.ItemGroup>
<SeedAttachmentInput.Context>
{typeof children === "function"
? children
: ({ acceptedFileEntries, updateFileEntryStatus }) =>
acceptedFileEntries.map((fileEntry, index) => (
<SortableAttachmentInputItem
key={fileEntry.id}
fileEntry={fileEntry}
index={index}
{...(onRetry && {
onRetry: () => onRetry(fileEntry, { updateFileEntryStatus }),
})}
/>
))}
</SeedAttachmentInput.Context>
</SeedAttachmentInput.ItemGroup>
</SeedAttachmentInput.Container>
</DragDropProvider>
</>
);
};
AttachmentDropzoneReorderable.displayName = "AttachmentDropzoneReorderable";
interface SortableAttachmentInputItemProps extends AttachmentInputItemProps {
index: number;
}
export const SortableAttachmentInputItem = React.forwardRef<
HTMLLIElement,
SortableAttachmentInputItemProps
>(({ fileEntry, index, ...props }, _ref) => {
const { readOnly } = useFileUploadContext();
const { ref: sortableRef } = useSortable({
id: fileEntry.id,
index,
disabled: readOnly,
modifiers: [RestrictToHorizontalAxis],
data: { name: fileEntry.file.name },
});
return <AttachmentInputItem ref={sortableRef} fileEntry={fileEntry} {...props} />;
});
SortableAttachmentInputItem.displayName = "SortableAttachmentInputItem";
/**
* This file is a snippet from Crispy, helping you get started quickly with @seed-design/* packages.
* You can extend this snippet however you want.
*/
Props
AttachmentField
Prop
Type
label?React.ReactNodeindicator?React.ReactNodedescription?React.ReactNodeerrorMessage?React.ReactNodeshowRequiredIndicator?boolean | undefinedinputProps?React.InputHTMLAttributes<HTMLInputElement> | undefinedfieldRef?React.Ref<HTMLDivElement> | undefinedrootProps?React.HTMLAttributes<HTMLDivElement> | undefinedname?string | undefinedacceptedFileEntries?FileEntry[] | undefineddefaultAcceptedFileEntries?FileEntry[] | undefinedonAcceptedFileEntriesChange?((fileEntries: FileEntry[]) => void) | undefinedonFileReject?((rejections: FileRejection[]) => void) | undefinedonFileAccept?((acceptedEntries: FileEntry[], helpers: { updateFileEntryStatus: (id: string, details: FileStatusDetails) => void; }) => void) | undefinedAttachmentInput
Prop
Type
children?((context: UseFileUploadContext) => React.ReactNode) | undefinedonRetry?((fileEntry: FileEntry, helpers: Pick<UseFileUploadReturn, "updateFileEntryStatus">) => void) | undefinedAttachmentDropzone
Prop
Type
children?((context: UseFileUploadContext) => React.ReactNode) | undefinedonRetry?((fileEntry: FileEntry, helpers: Pick<UseFileUploadReturn, "updateFileEntryStatus">) => void) | undefinedAttachmentInputItem
Prop
Type
onRetry?(() => void) | undefinedfileEntryFileEntryUsage
Basic usage
Use by combining one of AttachmentInput, AttachmentDropzone, AttachmentInputReorderable, or AttachmentDropzoneReorderable inside AttachmentField.
import {
AttachmentField,
AttachmentInput,
AttachmentDropzone,
} from "seed-design/ui/attachment-field";
<AttachmentField>
<AttachmentInput />
</AttachmentField>;
<AttachmentField>
<AttachmentDropzone />
</AttachmentField>;import { AttachmentField } from "seed-design/ui/attachment-field";
import {
AttachmentInputReorderable,
AttachmentDropzoneReorderable,
} from "seed-design/ui/attachment-field-reorderable";
<AttachmentField>
<AttachmentInputReorderable />
</AttachmentField>;
<AttachmentField>
<AttachmentDropzoneReorderable />
</AttachmentField>;Building Items Directly
AttachmentInput, AttachmentDropzone, AttachmentInputReorderable, and AttachmentDropzoneReorderable use children as a render prop.
You can use acceptedFileEntries to render AttachmentInputItem directly. In this case, it's recommended to use the id provided by the FileEntry type as the key.
If children is not provided, the files registered in acceptedFileEntries are automatically rendered as AttachmentInputItem.
import {
AttachmentField,
AttachmentInput,
AttachmentInputItem,
} from "seed-design/ui/attachment-field";
<AttachmentField>
<AttachmentInput>
{({ acceptedFileEntries }) =>
acceptedFileEntries.map((entry) => (
<AttachmentInputItem key={entry.id} fileEntry={entry} />
))
}
</AttachmentInput>
</AttachmentField>;Uploading Files
Trigger
Using AttachmentInput lets you use a layout that includes a trigger (upload button).
import type { FileEntry } from "@seed-design/react/primitive";
import { AttachmentField, AttachmentInput } from "seed-design/ui/attachment-field";
const defaultAcceptedFileEntries: FileEntry[] = [
{
id: "1",
file: new File(["hello"], "document.pdf", { type: "application/pdf" }),
status: "success",
},
];
export default function AttachmentFieldTriggerExample() {
return (
<AttachmentField
maxFiles={3}
label="파일 업로드"
defaultAcceptedFileEntries={defaultAcceptedFileEntries}
>
<AttachmentInput />
</AttachmentField>
);
}Dropzone
Using AttachmentDropzone lets you use a layout that includes a drag-and-drop area.
import { VStack } from "@seed-design/react";
import type { FileEntry } from "@seed-design/react/primitive";
import { AttachmentField, AttachmentDropzone } from "seed-design/ui/attachment-field";
const defaultAcceptedFileEntries: FileEntry[] = [
{
id: "1",
file: new File(["hello"], "document.pdf", { type: "application/pdf" }),
status: "success",
},
];
export default function AttachmentFieldDropzone() {
return (
<VStack gap="x4" p="x6" width="100%">
<AttachmentField
maxFiles={5}
label="파일 업로드"
description="파일을 선택하거나 드래그 앤 드롭하세요"
defaultAcceptedFileEntries={defaultAcceptedFileEntries}
>
<AttachmentDropzone />
</AttachmentField>
</VStack>
);
}Listening to Accepted File Changes
acceptedFileEntries is the list of files that have passed validation. You can detect change events for files registered in acceptedFileEntries with the onAcceptedFileEntriesChange callback.
import { VStack, Text } from "@seed-design/react";
import { useState } from "react";
import type { FileStatusDetails } from "@seed-design/react/primitive";
import {
AttachmentField,
AttachmentInput,
AttachmentInputItem,
} from "seed-design/ui/attachment-field";
function simulateUpload(
_file: File,
id: string,
updateFileEntryStatus: (id: string, details: FileStatusDetails) => void,
) {
updateFileEntryStatus(id, { status: "uploading", progress: 0 });
let progress = 0;
const interval = setInterval(() => {
progress += 25;
if (progress >= 100) {
clearInterval(interval);
updateFileEntryStatus(id, { status: "success" });
} else {
updateFileEntryStatus(id, { status: "uploading", progress });
}
}, 500);
}
export default function AttachmentFieldValueChanges() {
const [logs, setLogs] = useState<string[]>([]);
const addLog = (message: string) => {
setLogs((prev) => [...prev, `[${new Date().toLocaleTimeString()}] ${message}`]);
};
return (
<VStack gap="x4" width="100%" alignItems="center">
<VStack gap="x1">
{logs.length === 0 ? (
<Text color="fg.neutralMuted">파일을 추가하거나 삭제하면 로그가 표시됩니다.</Text>
) : (
logs.map((log, index) => (
<Text key={index} fontSize="fontSize.caption1">
{log}
</Text>
))
)}
</VStack>
<AttachmentField
maxFiles={3}
label="파일 업로드"
description="콜백 호출 로그를 확인하세요"
onFileAccept={(entries, { updateFileEntryStatus }) => {
addLog(`onFileAccept: ${entries.map((e) => e.file.name).join(", ")}`);
for (const entry of entries) {
simulateUpload(entry.file, entry.id, updateFileEntryStatus);
}
}}
onAcceptedFileEntriesChange={(files) => {
addLog(
`onAcceptedFileEntriesChange: ${files.map((f) => `${f.file.name} (${f.status})`).join(", ")}`,
);
}}
onFileReject={(files) => {
addLog(
`onFileReject: ${files.map((f) => `${f.file.name} (${f.errors.join(", ")})`).join(", ")}`,
);
}}
>
<AttachmentInput>
{({ acceptedFileEntries }) =>
acceptedFileEntries.map((fileEntry) => (
<AttachmentInputItem key={fileEntry.id} fileEntry={fileEntry} />
))
}
</AttachmentInput>
</AttachmentField>
</VStack>
);
}Validating Files
You can validate a file the user selected before it's registered in acceptedFileEntries.
The onFileReject callback runs for each invalid file. In that callback, you can check the file and the error codes to display an error message.
Max Files
You can limit the maximum number of uploadable files with maxFiles. The default value is 1. Once the maximum is reached, the trigger and dropzone are disabled.
If more files are selected than can be uploaded, files up to the uploadable limit are registered in acceptedFileEntries. The onFileReject callback runs for each of the remaining files. In this case, the error for the rejected files is "TOO_MANY_FILES".
import { VStack } from "@seed-design/react";
import type { FileEntry } from "@seed-design/react/primitive";
import { AttachmentField, AttachmentInput } from "seed-design/ui/attachment-field";
const defaultAcceptedFileEntries: FileEntry[] = [
{
id: "1",
file: new File(["hello"], "document.pdf", { type: "application/pdf" }),
status: "success",
},
];
export default function AttachmentFieldMaxFiles() {
return (
<VStack gap="x4" p="x6" width="100%">
<AttachmentField
maxFiles={3}
label="파일 업로드"
description="최대 3개까지 업로드할 수 있습니다"
defaultAcceptedFileEntries={defaultAcceptedFileEntries}
>
<AttachmentInput />
</AttachmentField>
</VStack>
);
}Invalid File Type
You can restrict the kinds of files that can be uploaded with accept.
You can specify a MIME type (image/png, image/*) or an extension (.png, .jpg, .jpeg) format, and if you pass a string[], each string is joined with ,.
Restricting the kinds of files a user can select via the accept attribute registered on <input type="file"> is only a convenience feature that works in the browser UI. So users can still select files of a restricted kind through a feature like Show all files in the browser's file selection dialog. Files selected this way trigger the onFileReject callback with an "INVALID_TYPE" error.
If file type validation is required, that validation must also be performed on the server.
import { useState } from "react";
import { VStack } from "@seed-design/react";
import { AttachmentField, AttachmentInput } from "seed-design/ui/attachment-field";
function getErrorMessage(errorCode: string): string {
switch (errorCode) {
case "INVALID_TYPE":
return "지원하지 않는 파일 형식입니다";
default:
return "업로드에 실패했습니다";
}
}
export default function AttachmentFieldInvalidFileType() {
const [errorMessage, setErrorMessage] = useState<string>();
return (
<VStack gap="x4" p="x6" width="100%">
<AttachmentField
accept={["image/png", "image/jpeg"]}
maxFiles={3}
invalid={!!errorMessage}
errorMessage={errorMessage}
label="이미지 업로드"
description="PNG, JPEG 파일만 업로드할 수 있습니다"
onAcceptedFileEntriesChange={() => setErrorMessage(undefined)}
onFileReject={(files) => {
const messages = files.map(
({ file, errors }) => `"${file.name}": ${errors.map(getErrorMessage).join(", ")}`,
);
setErrorMessage(messages.join("\n"));
}}
>
<AttachmentInput />
</AttachmentField>
</VStack>
);
}File Size
You can use the minFileSize and maxFileSize props.
- If a file the user selected is smaller than
minFileSize, theonFileRejectcallback runs with a"FILE_TOO_SMALL"error. - If a file the user selected is larger than
maxFileSize, theonFileRejectcallback runs with a"FILE_TOO_LARGE"error.
import { useState } from "react";
import { VStack } from "@seed-design/react";
import { AttachmentField, AttachmentInput } from "seed-design/ui/attachment-field";
import { formatBytes } from "seed-design/lib/format-bytes";
const MIN_FILE_SIZE = 1 * 1024; // 1KB
const MAX_FILE_SIZE = 10 * 1024; // 10KB
function getErrorMessage(errorCode: string): string {
switch (errorCode) {
case "FILE_TOO_LARGE":
return `크기가 ${formatBytes(MAX_FILE_SIZE)}를 초과합니다`;
case "FILE_TOO_SMALL":
return `크기가 ${formatBytes(MIN_FILE_SIZE)} 미만입니다`;
case "TOO_MANY_FILES":
return "업로드 가능한 파일 개수를 초과했습니다";
default:
return "업로드에 실패했습니다";
}
}
export default function AttachmentFieldValidation() {
const [errorMessage, setErrorMessage] = useState<string>();
return (
<VStack gap="x4" p="x6" width="100%">
<AttachmentField
maxFiles={3}
minFileSize={MIN_FILE_SIZE}
maxFileSize={MAX_FILE_SIZE}
invalid={!!errorMessage}
errorMessage={errorMessage}
label="파일 업로드"
description={`${formatBytes(MIN_FILE_SIZE)} ~ ${formatBytes(MAX_FILE_SIZE)} 크기의 파일만 업로드할 수 있습니다`}
onAcceptedFileEntriesChange={() => setErrorMessage(undefined)}
onFileReject={(files) => {
const messages = files.map(
({ file, errors }) => `"${file.name}": ${errors.map(getErrorMessage).join(", ")}`,
);
setErrorMessage(messages.join("\n"));
}}
>
<AttachmentInput />
</AttachmentField>
</VStack>
);
}Custom Validation
You can add your own validation for each file with the validate prop. By returning a custom error code, you can branch the message by error type in onFileReject.
import { useState } from "react";
import { VStack } from "@seed-design/react";
import { AttachmentField, AttachmentInput } from "seed-design/ui/attachment-field";
function validateFileName(file: File) {
const nameWithoutExt = file.name.replace(/\.[^.]+$/, "");
if (nameWithoutExt.length > 8) {
return ["FILENAME_TOO_LONG"];
}
return null;
}
export default function AttachmentFieldCustomValidation() {
const [errorMessage, setErrorMessage] = useState<string>();
return (
<VStack gap="x4" p="x6" width="100%">
<AttachmentField
maxFiles={5}
validate={validateFileName}
invalid={!!errorMessage}
errorMessage={errorMessage}
label="파일 업로드"
description="파일 이름은 확장자를 제외하고 8자 이하여야 합니다"
onAcceptedFileEntriesChange={() => setErrorMessage(undefined)}
onFileReject={(files) => {
if (files.every((f) => f.errors.includes("FILENAME_TOO_LONG")) === false) {
return;
}
const names = files.map((f) => f.file.name).join(", ");
setErrorMessage(`"${names}"은(는) 파일 이름이 8자를 초과합니다.`);
}}
>
<AttachmentInput />
</AttachmentField>
</VStack>
);
}Managing File Status
Each item in acceptedFileEntries can have a status of pending, uploading, success, or error. The default status for a newly added item is pending.
If you integrate with an external upload API right after file selection, you can show the user the uploading status of each file item. Receive the newly added file in the onFileAccept callback, and use the updateFileEntryStatus helper provided alongside it to update the item's status.
import { useCallback } from "react";
import { VStack } from "@seed-design/react";
import type { FileStatusDetails } from "@seed-design/react/primitive";
import {
AttachmentField,
AttachmentInput,
AttachmentInputItem,
} from "seed-design/ui/attachment-field";
// 실제 환경에서는 fetch 등으로 교체하세요.
async function uploadFile(
file: File,
onProgress: (progress: number) => void,
): Promise<{ url: string }> {
const totalChunks = 5;
for (let i = 1; i <= totalChunks; i++) {
await new Promise((r) => setTimeout(r, 200 + Math.random() * 300));
onProgress(Math.round((i / totalChunks) * 100));
}
if (Math.random() > 0.5) {
throw new Error("Network error");
}
return { url: `https://example.com/uploads/${file.name}` };
}
export default function AttachmentFieldStatus() {
const startUpload = useCallback(
(
file: File,
id: string,
updateFileEntryStatus: (id: string, details: FileStatusDetails) => void,
) => {
updateFileEntryStatus(id, { status: "uploading", progress: 0 });
uploadFile(file, (progress) => {
updateFileEntryStatus(id, { status: "uploading", progress });
})
.then(() => updateFileEntryStatus(id, { status: "success" }))
.catch(() => updateFileEntryStatus(id, { status: "error" }));
},
[],
);
return (
<VStack gap="x4" p="x6" width="100%">
<AttachmentField
accept="image/*"
maxFiles={5}
label="파일 업로드"
description="업로드 상태 시뮬레이션"
onFileAccept={(entries, { updateFileEntryStatus }) => {
for (const entry of entries) {
startUpload(entry.file, entry.id, updateFileEntryStatus);
}
}}
>
<AttachmentInput>
{({ acceptedFileEntries, updateFileEntryStatus }) =>
acceptedFileEntries.map((fileEntry) => (
<AttachmentInputItem
key={fileEntry.id}
fileEntry={fileEntry}
onRetry={() => startUpload(fileEntry.file, fileEntry.id, updateFileEntryStatus)}
/>
))
}
</AttachmentInput>
</AttachmentField>
</VStack>
);
}uploading: A ProgressCircle is shown.- You can set
progressto display the upload progress. - If
progressis not set, it's shown in the indeterminate state.
- You can set
error: A retry button is shown.- When clicked, the
onRetrycallback set onAttachmentInputItemruns.
- When clicked, the
A file item that passed validation remains in acceptedFileEntries regardless of its status, so it's included when a native form is submitted.
Reordering Files
Using AttachmentInputReorderable or AttachmentDropzoneReorderable lets you change the order of files by dragging.
Both components are provided as a separate snippet, ui:attachment-field-reorderable, to keep the dnd-kit dependency isolated.
Since reorderFileEntry is provided via Context, you can implement your own drag-and-drop behavior if needed, or integrate with a drag-and-drop library your project is already using.
import type { FileEntry } from "@seed-design/react/primitive";
import { AttachmentField } from "seed-design/ui/attachment-field";
import { AttachmentInputReorderable } from "seed-design/ui/attachment-field-reorderable";
function createMockImageFile(name: string, base64: string): File {
const bytes = Uint8Array.from(atob(base64), (c) => c.charCodeAt(0));
return new File([bytes], name, { type: "image/png" });
}
const defaultAcceptedFileEntries: FileEntry[] = [
{
id: "1",
file: createMockImageFile(
"sunset-landscape.png",
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR4nGN4FcEDAAN+AU+hW/ICAAAAAElFTkSuQmCC",
),
status: "success",
},
{
id: "2",
file: createMockImageFile(
"city-night.png",
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR4nGOYbPwKAAMNAbHKe2UaAAAAAElFTkSuQmCC",
),
status: "success",
},
{
id: "3",
file: createMockImageFile(
"morning-coffee.png",
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR4nGN4tZkDAAQwAaYlKXDxAAAAAElFTkSuQmCC",
),
status: "success",
},
];
export default function AttachmentFieldReorderableExample() {
return (
<AttachmentField
accept="image/*"
maxFiles={5}
label="이미지 업로드"
description="드래그하여 순서를 변경할 수 있습니다"
defaultAcceptedFileEntries={defaultAcceptedFileEntries}
>
<AttachmentInputReorderable />
</AttachmentField>
);
}Examples
Showing Thumbnails
To show an image preview instead of the file name and size, restrict the user to selecting only image files by setting accept to something like "image/*" or ["image/png", "image/jpeg"].
import { VStack } from "@seed-design/react";
import { AttachmentField, AttachmentInput } from "seed-design/ui/attachment-field";
export default function AttachmentFieldAcceptImage() {
return (
<VStack gap="x4" p="x6" width="100%">
<AttachmentField
accept="image/*"
maxFiles={5}
label="이미지 업로드"
description="이미지 파일만 허용됩니다"
>
<AttachmentInput />
</AttachmentField>
</VStack>
);
}For some image formats such as "image/heic", the
image preview may not display depending on the browser.
Disabled
The disabled prop disables the trigger and dropzone to block new file selection, and marks <input type="file"> as disabled so its value is not sent when the form is submitted.
import { VStack } from "@seed-design/react";
import type { FileEntry } from "@seed-design/react/primitive";
import { AttachmentField, AttachmentInput } from "seed-design/ui/attachment-field";
const defaultFiles: FileEntry[] = [
{
id: "mock-1",
file: new File(["hello"], "document.pdf", { type: "application/pdf" }),
status: "success",
},
{
id: "mock-2",
file: new File(["world"], "image.png", { type: "image/png" }),
status: "success",
},
];
export default function AttachmentFieldDisabled() {
return (
<VStack gap="x4" p="x6" width="100%">
<AttachmentField
disabled
maxFiles={5}
defaultAcceptedFileEntries={defaultFiles}
label="파일 업로드"
description="비활성화된 AttachmentField"
>
<AttachmentInput />
</AttachmentField>
</VStack>
);
}Read Only
You can display attached files as read-only with the readOnly prop. The trigger, dropzone, file remove button, and reordering are all disabled, but the value of <input type="file"> is preserved and sent along when the form is submitted.
import { VStack } from "@seed-design/react";
import type { FileEntry } from "@seed-design/react/primitive";
import { AttachmentField, AttachmentInput } from "seed-design/ui/attachment-field";
const defaultFiles: FileEntry[] = [
{
id: "mock-1",
file: new File(["hello"], "document.pdf", { type: "application/pdf" }),
status: "success",
},
{
id: "mock-2",
file: new File(["world"], "image.png", { type: "image/png" }),
status: "success",
},
];
export default function AttachmentFieldReadOnly() {
return (
<VStack gap="x4" p="x6" width="100%">
<AttachmentField
readOnly
maxFiles={5}
defaultAcceptedFileEntries={defaultFiles}
label="첨부 파일"
description="읽기 전용 상태"
>
<AttachmentInput />
</AttachmentField>
</VStack>
);
}Controlled
You can control the file list externally using acceptedFileEntries and onAcceptedFileEntriesChange.
import { VStack, HStack, Text } from "@seed-design/react";
import { useState } from "react";
import { ActionButton } from "seed-design/ui/action-button";
import type { FileEntry } from "@seed-design/react/primitive";
import { AttachmentField, AttachmentInput } from "seed-design/ui/attachment-field";
export default function AttachmentFieldControlled() {
const [acceptedFileEntries, setAcceptedFileEntries] = useState<FileEntry[]>([]);
return (
<VStack gap="x4" width="100%">
<AttachmentField
maxFiles={5}
label="Controlled"
description="최대 5개까지 업로드할 수 있습니다"
acceptedFileEntries={acceptedFileEntries}
onAcceptedFileEntriesChange={setAcceptedFileEntries}
>
<AttachmentInput />
</AttachmentField>
<Text>현재 파일: {JSON.stringify(acceptedFileEntries.map((f) => f.file.name))}</Text>
<HStack gap="x2">
<ActionButton
type="button"
variant="neutralWeak"
onClick={() => setAcceptedFileEntries([])}
>
전체 삭제
</ActionButton>
</HStack>
</VStack>
);
}Custom Inset
You can use the --seed-attachment-input-extend-x CSS variable to configure the scrolling item list to extend beyond the layout.
import { VStack } from "@seed-design/react";
import { AttachmentField, AttachmentInput } from "seed-design/ui/attachment-field";
import { TextField, TextFieldInput } from "seed-design/ui/text-field";
import { vars } from "@seed-design/css/vars";
const mockedFiles = Array.from({ length: 8 }, (_, i) => {
const file = new File(["file content"], `file${i + 1}.txt`, { type: "text/plain" });
Object.defineProperty(file, "size", { value: 1 });
return file;
});
export default function AttachmentFieldCustomInset() {
return (
<VStack
px="spacingX.globalGutter"
width="400px"
maxWidth="full"
bg="palette.gray300"
borderWidth={1}
borderColor="stroke.neutralMuted"
>
<VStack gap="spacingY.componentDefault" bg="bg.layerDefault">
<TextField label="이름">
<TextFieldInput placeholder="홍길동" />
</TextField>
<AttachmentField
maxFiles={5}
label="첨부파일"
defaultAcceptedFileEntries={mockedFiles.map((file, index) => ({
id: `${index}`,
file,
status: "pending",
}))}
rootProps={{
style: {
"--seed-attachment-input-extend-x": vars.$dimension.spacingX.globalGutter,
} as React.CSSProperties,
}}
>
<AttachmentInput />
</AttachmentField>
</VStack>
</VStack>
);
}Field Integration
You can use Field-related props such as label, description, and errorMessage.
import { Divider, VStack } from "@seed-design/react";
import { AttachmentField, AttachmentInput } from "seed-design/ui/attachment-field";
export default function AttachmentFieldField() {
return (
<VStack gap="x8" width="100%">
<AttachmentField
maxFiles={3}
label="첨부파일"
labelWeight="bold"
required
showRequiredIndicator
invalid
errorMessage="필수 항목입니다."
>
<AttachmentInput />
</AttachmentField>
<Divider />
<AttachmentField
maxFiles={3}
label="첨부파일"
description="파일을 선택하거나 드래그 앤 드롭하세요."
indicator="선택"
>
<AttachmentInput />
</AttachmentField>
</VStack>
);
}Form (Uncontrolled)
Files registered in acceptedFileEntries are synced to the files of <input type="file">, so you can use <form> and the name prop to include them in the formData.
import { VStack } from "@seed-design/react";
import { useState, type FormEvent } from "react";
import { ActionButton } from "seed-design/ui/action-button";
import { AttachmentField, AttachmentInput } from "seed-design/ui/attachment-field";
type FieldErrors = {
files?: string;
};
export default function AttachmentFieldForm() {
const [fieldErrors, setFieldErrors] = useState<FieldErrors>({});
const handleSubmit = (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
const formData = new FormData(event.currentTarget);
const files = formData.getAll("files") as File[];
if (files.length === 0) {
setFieldErrors({ files: "최소 1개의 파일을 업로드해주세요" });
return;
}
window.alert(`제출된 파일: ${files.map((f) => f.name).join(", ")}`);
};
return (
<VStack asChild gap="x3" width="full">
<form onSubmit={handleSubmit}>
<AttachmentField
name="files"
maxFiles={3}
label="첨부파일"
description="최대 3개까지 업로드할 수 있습니다"
required
showRequiredIndicator
onAcceptedFileEntriesChange={(files) => {
if (files.length > 0) {
setFieldErrors({});
}
}}
{...(fieldErrors.files && { invalid: true, errorMessage: fieldErrors.files })}
>
<AttachmentInput />
</AttachmentField>
<ActionButton type="submit" variant="neutralSolid">
제출
</ActionButton>
</form>
</VStack>
);
}React Hook Form
import { HStack, VStack } from "@seed-design/react";
import { useCallback, type FormEvent } from "react";
import { useController, useForm } from "react-hook-form";
import { ActionButton } from "seed-design/ui/action-button";
import type { FileEntry } from "@seed-design/react/primitive";
import { AttachmentField, AttachmentInput } from "seed-design/ui/attachment-field";
interface FormValues {
files: FileEntry[];
}
export default function AttachmentFieldReactHookForm() {
const { handleSubmit, reset, control } = useForm<FormValues>({
reValidateMode: "onSubmit",
defaultValues: {
files: [],
},
});
const {
field: { value, onChange, ...field },
fieldState,
} = useController({
name: "files",
control,
rules: {
validate: (value) => value.length > 0 || "최소 1개의 파일을 업로드해주세요",
},
});
const onValid = useCallback(
(data: FormValues) =>
window.alert(`제출된 파일: ${data.files.map((f) => f.file.name).join(", ")}`),
[],
);
const onReset = useCallback(
(event: FormEvent) => {
event.preventDefault();
reset();
},
[reset],
);
return (
<VStack gap="x3" width="full" as="form" onSubmit={handleSubmit(onValid)} onReset={onReset}>
<AttachmentField
maxFiles={5}
label="첨부파일"
description="최대 5개까지 업로드할 수 있습니다"
showRequiredIndicator
invalid={fieldState.invalid}
errorMessage={fieldState.error?.message}
acceptedFileEntries={value}
onAcceptedFileEntriesChange={onChange}
{...field}
>
<AttachmentInput />
</AttachmentField>
<HStack gap="x2">
<ActionButton type="reset" variant="neutralWeak">
초기화
</ActionButton>
<ActionButton type="submit" variant="neutralSolid" flexGrow={1}>
제출
</ActionButton>
</HStack>
</VStack>
);
}Customizing Items
If you need additional customization beyond the default item layout provided by the snippet, you can build the item yourself using elements such as AttachmentInput.ItemBadge provided by @seed-design/react.
In the example below, AttachmentInput.ItemBadge is used to show a "Main photo" badge on the first image.
"use client";
import { AttachmentInput as SeedAttachmentInput, Icon, VStack } from "@seed-design/react";
import type { FileEntry } from "@seed-design/react/primitive";
import { IconArrowClockwiseCircularFill, IconXmarkFill } from "@karrotmarket/react-monochrome-icon";
import { AttachmentField, AttachmentInput } from "seed-design/ui/attachment-field";
import { ProgressCircle } from "seed-design/ui/progress-circle";
const LABEL_REMOVE_FILE = "파일 제거";
const LABEL_RETRY = "재시도";
function CustomImageItem({
fileEntry,
isCover,
onRetry,
}: {
fileEntry: FileEntry;
isCover?: boolean;
onRetry?: () => void;
}) {
return (
<SeedAttachmentInput.Item fileEntry={fileEntry}>
<SeedAttachmentInput.ItemImage />
{isCover && <SeedAttachmentInput.ItemBadge>대표사진</SeedAttachmentInput.ItemBadge>}
<SeedAttachmentInput.ItemBackdrop status="uploading">
{(entry) => (
<ProgressCircle
size="24"
tone="staticWhite"
{...("progress" in entry && { value: entry.progress })}
/>
)}
</SeedAttachmentInput.ItemBackdrop>
{onRetry && (
<SeedAttachmentInput.ItemBackdrop status="error">
<SeedAttachmentInput.ItemActionButton onClick={onRetry}>
<Icon svg={<IconArrowClockwiseCircularFill />} />
{LABEL_RETRY}
</SeedAttachmentInput.ItemActionButton>
</SeedAttachmentInput.ItemBackdrop>
)}
<SeedAttachmentInput.ItemRemoveButton aria-label={LABEL_REMOVE_FILE}>
<Icon svg={<IconXmarkFill />} />
</SeedAttachmentInput.ItemRemoveButton>
</SeedAttachmentInput.Item>
);
}
export default function AttachmentFieldCustomizingItems() {
return (
<VStack gap="x4" p="x6" width="100%">
<AttachmentField
accept="image/*"
maxFiles={10}
label="이미지 업로드"
description="첫 번째 이미지가 대표사진으로 설정됩니다"
>
<AttachmentInput>
{({ acceptedFileEntries }) =>
acceptedFileEntries.map((fileEntry, index) => (
<CustomImageItem key={fileEntry.id} fileEntry={fileEntry} isCover={index === 0} />
))
}
</AttachmentInput>
</AttachmentField>
</VStack>
);
}