Attachment Display Field
A component for displaying and managing media from external sources based on URLs.
import { VStack } from "@seed-design/react";
import type { DisplayItemEntry } from "@seed-design/react/primitive";
import { AttachmentDisplay, AttachmentDisplayField } from "seed-design/ui/attachment-display-field";
const sampleEntries: DisplayItemEntry[] = [
{
id: "1",
thumbnailUrl: "https://picsum.photos/seed/seed1/200/200",
status: "success",
},
{
id: "2",
thumbnailUrl: "https://picsum.photos/seed/seed2/200/200",
status: "success",
},
];
// 외부 미디어 피커 모킹. 실제 환경에서는 네이티브 브릿지/모달/서버 호출 등으로 교체하세요.
async function openMediaPicker(): Promise<DisplayItemEntry[]> {
const id = crypto.randomUUID();
return [
{
id,
thumbnailUrl: `https://picsum.photos/seed/${id}/200/200`,
status: "success",
},
];
}
export default function AttachmentDisplayPreview() {
return (
<VStack gap="x4" p="x6" width="100%">
<AttachmentDisplayField defaultEntries={sampleEntries} maxEntries={5}>
<AttachmentDisplay
onTriggerClick={async ({ addEntries }) => {
addEntries(await openMediaPicker());
}}
/>
</AttachmentDisplayField>
</VStack>
);
}Installation
Default
Includes components that can be used when reordering is not needed.
npx @seed-design/cli@latest add ui:attachment-display-fieldpnpm dlx @seed-design/cli@latest add ui:attachment-display-fieldyarn dlx @seed-design/cli@latest add ui:attachment-display-fieldbun x @seed-design/cli@latest add ui:attachment-display-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-display-field
* @requires @seed-design/react@^2.0.0
* @requires @seed-design/css@^2.0.0
**/
"use client";
import {
IconArrowClockwiseCircularFill,
IconCameraFill,
IconExclamationmarkCircleFill,
IconXmarkFill,
} from "@karrotmarket/react-monochrome-icon";
import type { FieldLabelVariantProps } from "@seed-design/css/recipes/field-label";
import {
AttachmentDisplay as SeedAttachmentDisplay,
Icon,
PrefixIcon,
VisuallyHidden,
} from "@seed-design/react";
import {
type DisplayItemEntry,
type UseAttachmentDisplayReturn,
useAttachmentDisplayContext,
} from "@seed-design/react/primitive";
import * as React from "react";
import { ProgressCircle } from "./progress-circle";
// You may implement your own i18n for these labels
const LABEL_SELECT_FILE = "파일 선택";
const LABEL_RETRY = "재시도";
const LABEL_REMOVE = "파일 제거";
export interface AttachmentDisplayFieldProps
extends Omit<SeedAttachmentDisplay.RootProps, "asChild"> {
label?: React.ReactNode;
/**
* @default "medium"
*/
labelWeight?: FieldLabelVariantProps["weight"];
indicator?: React.ReactNode;
description?: React.ReactNode;
errorMessage?: React.ReactNode;
showRequiredIndicator?: boolean;
}
/**
* @see https://crispy.carrot-soft.tech/react/components/attachment-display-field
*/
export const AttachmentDisplayField = React.forwardRef<HTMLDivElement, AttachmentDisplayFieldProps>(
(
{
label,
labelWeight,
indicator,
description,
errorMessage,
showRequiredIndicator,
children,
...props
},
ref,
) => {
const renderHeader = label || indicator;
const renderDescription = !!description;
const renderErrorMessage = errorMessage && props.invalid;
const renderFooter = renderDescription || renderErrorMessage;
return (
<SeedAttachmentDisplay.Root ref={ref} {...props}>
{renderHeader && (
<SeedAttachmentDisplay.Header>
<SeedAttachmentDisplay.Label weight={labelWeight}>
{label}
{showRequiredIndicator && <SeedAttachmentDisplay.RequiredIndicator />}
{indicator && (
<SeedAttachmentDisplay.IndicatorText>
{indicator}
</SeedAttachmentDisplay.IndicatorText>
)}
</SeedAttachmentDisplay.Label>
{/* You might want to put your custom element here */}
</SeedAttachmentDisplay.Header>
)}
<SeedAttachmentDisplay.Control>{children}</SeedAttachmentDisplay.Control>
{renderFooter && (
<SeedAttachmentDisplay.Footer>
{renderDescription &&
(renderErrorMessage ? (
<VisuallyHidden asChild>
<SeedAttachmentDisplay.Description>
{description}
</SeedAttachmentDisplay.Description>
</VisuallyHidden>
) : (
<SeedAttachmentDisplay.Description>{description}</SeedAttachmentDisplay.Description>
))}
{renderErrorMessage && (
<SeedAttachmentDisplay.ErrorMessage>
<PrefixIcon svg={<IconExclamationmarkCircleFill />} />
{errorMessage}
</SeedAttachmentDisplay.ErrorMessage>
)}
</SeedAttachmentDisplay.Footer>
)}
</SeedAttachmentDisplay.Root>
);
},
);
AttachmentDisplayField.displayName = "AttachmentDisplayField";
export type AttachmentDisplayProps = {
onTriggerClick: (
helpers: Pick<UseAttachmentDisplayReturn, "addEntries" | "updateEntryStatus">,
) => void;
} & (
| { children: SeedAttachmentDisplay.ContextProps["children"]; onRetry?: never }
| {
children?: undefined;
onRetry?: (
entry: DisplayItemEntry,
helpers: Pick<UseAttachmentDisplayReturn, "updateEntryStatus">,
) => void;
}
);
/**
* @see https://crispy.carrot-soft.tech/react/components/attachment-display-field
*/
export const AttachmentDisplay = React.forwardRef<HTMLDivElement, AttachmentDisplayProps>(
({ onTriggerClick, children, onRetry }, ref) => {
const { addEntries, updateEntryStatus } = useAttachmentDisplayContext();
return (
<SeedAttachmentDisplay.Container ref={ref}>
<SeedAttachmentDisplay.Trigger
onClick={() => onTriggerClick({ addEntries, updateEntryStatus })}
aria-label={LABEL_SELECT_FILE}
>
<SeedAttachmentDisplay.TriggerIcon image={<IconCameraFill />} />
<SeedAttachmentDisplay.TriggerItemCount />
</SeedAttachmentDisplay.Trigger>
<SeedAttachmentDisplay.ItemGroup>
<SeedAttachmentDisplay.Context>
{typeof children === "function"
? children
: ({ entries }) =>
entries.map((entry) => (
<AttachmentDisplayItem
key={entry.id}
entry={entry}
{...(onRetry && { onRetry: () => onRetry(entry, { updateEntryStatus }) })}
/>
))}
</SeedAttachmentDisplay.Context>
</SeedAttachmentDisplay.ItemGroup>
</SeedAttachmentDisplay.Container>
);
},
);
AttachmentDisplay.displayName = "AttachmentDisplay";
export interface AttachmentDisplayItemProps
extends Omit<SeedAttachmentDisplay.ItemProps, "children"> {
onRetry?: () => void;
}
/**
* @see https://crispy.carrot-soft.tech/react/components/attachment-display-field
*/
export const AttachmentDisplayItem = React.forwardRef<HTMLLIElement, AttachmentDisplayItemProps>(
({ onRetry, ...props }, ref) => {
return (
<SeedAttachmentDisplay.Item ref={ref} {...props}>
<SeedAttachmentDisplay.ItemImage />
<SeedAttachmentDisplay.ItemBackdrop status="uploading">
{(entry) => (
<ProgressCircle
size="24"
tone="staticWhite"
{...("progress" in entry && { value: entry.progress })}
/>
)}
</SeedAttachmentDisplay.ItemBackdrop>
{onRetry && (
<SeedAttachmentDisplay.ItemBackdrop status="error">
<SeedAttachmentDisplay.ItemActionButton onClick={onRetry}>
<Icon svg={<IconArrowClockwiseCircularFill />} />
{LABEL_RETRY}
</SeedAttachmentDisplay.ItemActionButton>
</SeedAttachmentDisplay.ItemBackdrop>
)}
<SeedAttachmentDisplay.ItemRemoveButton aria-label={LABEL_REMOVE}>
<Icon svg={<IconXmarkFill />} />
</SeedAttachmentDisplay.ItemRemoveButton>
</SeedAttachmentDisplay.Item>
);
},
);
AttachmentDisplayItem.displayName = "AttachmentDisplayItem";
/**
* 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 items through drag and drop is needed. The dnd-kit dependency is added to the project.
npx @seed-design/cli@latest add ui:attachment-display-field-reorderablepnpm dlx @seed-design/cli@latest add ui:attachment-display-field-reorderableyarn dlx @seed-design/cli@latest add ui:attachment-display-field-reorderablebun x @seed-design/cli@latest add ui:attachment-display-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-display-field-reorderable
* @requires @seed-design/react@^2.0.0
* @requires @seed-design/css@^2.0.0
**/
"use client";
import {
IconArrowClockwiseCircularFill,
IconCameraFill,
IconExclamationmarkCircleFill,
IconXmarkFill,
} from "@karrotmarket/react-monochrome-icon";
import type { FieldLabelVariantProps } from "@seed-design/css/recipes/field-label";
import {
AttachmentDisplay as SeedAttachmentDisplay,
Icon,
PrefixIcon,
VisuallyHidden,
} from "@seed-design/react";
import {
type DisplayItemEntry,
type UseAttachmentDisplayReturn,
useAttachmentDisplayContext,
} from "@seed-design/react/primitive";
import * as React from "react";
import { ProgressCircle } from "./progress-circle";
// You may implement your own i18n for these labels
const LABEL_SELECT_FILE = "파일 선택";
const LABEL_RETRY = "재시도";
const LABEL_REMOVE = "파일 제거";
export interface AttachmentDisplayFieldProps
extends Omit<SeedAttachmentDisplay.RootProps, "asChild"> {
label?: React.ReactNode;
/**
* @default "medium"
*/
labelWeight?: FieldLabelVariantProps["weight"];
indicator?: React.ReactNode;
description?: React.ReactNode;
errorMessage?: React.ReactNode;
showRequiredIndicator?: boolean;
}
/**
* @see https://crispy.carrot-soft.tech/react/components/attachment-display-field
*/
export const AttachmentDisplayField = React.forwardRef<HTMLDivElement, AttachmentDisplayFieldProps>(
(
{
label,
labelWeight,
indicator,
description,
errorMessage,
showRequiredIndicator,
children,
...props
},
ref,
) => {
const renderHeader = label || indicator;
const renderDescription = !!description;
const renderErrorMessage = errorMessage && props.invalid;
const renderFooter = renderDescription || renderErrorMessage;
return (
<SeedAttachmentDisplay.Root ref={ref} {...props}>
{renderHeader && (
<SeedAttachmentDisplay.Header>
<SeedAttachmentDisplay.Label weight={labelWeight}>
{label}
{showRequiredIndicator && <SeedAttachmentDisplay.RequiredIndicator />}
{indicator && (
<SeedAttachmentDisplay.IndicatorText>
{indicator}
</SeedAttachmentDisplay.IndicatorText>
)}
</SeedAttachmentDisplay.Label>
{/* You might want to put your custom element here */}
</SeedAttachmentDisplay.Header>
)}
<SeedAttachmentDisplay.Control>{children}</SeedAttachmentDisplay.Control>
{renderFooter && (
<SeedAttachmentDisplay.Footer>
{renderDescription &&
(renderErrorMessage ? (
<VisuallyHidden asChild>
<SeedAttachmentDisplay.Description>
{description}
</SeedAttachmentDisplay.Description>
</VisuallyHidden>
) : (
<SeedAttachmentDisplay.Description>{description}</SeedAttachmentDisplay.Description>
))}
{renderErrorMessage && (
<SeedAttachmentDisplay.ErrorMessage>
<PrefixIcon svg={<IconExclamationmarkCircleFill />} />
{errorMessage}
</SeedAttachmentDisplay.ErrorMessage>
)}
</SeedAttachmentDisplay.Footer>
)}
</SeedAttachmentDisplay.Root>
);
},
);
AttachmentDisplayField.displayName = "AttachmentDisplayField";
export type AttachmentDisplayProps = {
onTriggerClick: (
helpers: Pick<UseAttachmentDisplayReturn, "addEntries" | "updateEntryStatus">,
) => void;
} & (
| { children: SeedAttachmentDisplay.ContextProps["children"]; onRetry?: never }
| {
children?: undefined;
onRetry?: (
entry: DisplayItemEntry,
helpers: Pick<UseAttachmentDisplayReturn, "updateEntryStatus">,
) => void;
}
);
/**
* @see https://crispy.carrot-soft.tech/react/components/attachment-display-field
*/
export const AttachmentDisplay = React.forwardRef<HTMLDivElement, AttachmentDisplayProps>(
({ onTriggerClick, children, onRetry }, ref) => {
const { addEntries, updateEntryStatus } = useAttachmentDisplayContext();
return (
<SeedAttachmentDisplay.Container ref={ref}>
<SeedAttachmentDisplay.Trigger
onClick={() => onTriggerClick({ addEntries, updateEntryStatus })}
aria-label={LABEL_SELECT_FILE}
>
<SeedAttachmentDisplay.TriggerIcon image={<IconCameraFill />} />
<SeedAttachmentDisplay.TriggerItemCount />
</SeedAttachmentDisplay.Trigger>
<SeedAttachmentDisplay.ItemGroup>
<SeedAttachmentDisplay.Context>
{typeof children === "function"
? children
: ({ entries }) =>
entries.map((entry) => (
<AttachmentDisplayItem
key={entry.id}
entry={entry}
{...(onRetry && { onRetry: () => onRetry(entry, { updateEntryStatus }) })}
/>
))}
</SeedAttachmentDisplay.Context>
</SeedAttachmentDisplay.ItemGroup>
</SeedAttachmentDisplay.Container>
);
},
);
AttachmentDisplay.displayName = "AttachmentDisplay";
export interface AttachmentDisplayItemProps
extends Omit<SeedAttachmentDisplay.ItemProps, "children"> {
onRetry?: () => void;
}
/**
* @see https://crispy.carrot-soft.tech/react/components/attachment-display-field
*/
export const AttachmentDisplayItem = React.forwardRef<HTMLLIElement, AttachmentDisplayItemProps>(
({ onRetry, ...props }, ref) => {
return (
<SeedAttachmentDisplay.Item ref={ref} {...props}>
<SeedAttachmentDisplay.ItemImage />
<SeedAttachmentDisplay.ItemBackdrop status="uploading">
{(entry) => (
<ProgressCircle
size="24"
tone="staticWhite"
{...("progress" in entry && { value: entry.progress })}
/>
)}
</SeedAttachmentDisplay.ItemBackdrop>
{onRetry && (
<SeedAttachmentDisplay.ItemBackdrop status="error">
<SeedAttachmentDisplay.ItemActionButton onClick={onRetry}>
<Icon svg={<IconArrowClockwiseCircularFill />} />
{LABEL_RETRY}
</SeedAttachmentDisplay.ItemActionButton>
</SeedAttachmentDisplay.ItemBackdrop>
)}
<SeedAttachmentDisplay.ItemRemoveButton aria-label={LABEL_REMOVE}>
<Icon svg={<IconXmarkFill />} />
</SeedAttachmentDisplay.ItemRemoveButton>
</SeedAttachmentDisplay.Item>
);
},
);
AttachmentDisplayItem.displayName = "AttachmentDisplayItem";
/**
* 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-display-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 { RestrictToHorizontalAxis } from "@dnd-kit/abstract/modifiers";
import { Accessibility, AutoScroller } from "@dnd-kit/dom";
import { DragDropProvider } from "@dnd-kit/react";
import { isSortable, useSortable } from "@dnd-kit/react/sortable";
import { IconCameraFill } from "@karrotmarket/react-monochrome-icon";
import { AttachmentDisplay as SeedAttachmentDisplay } from "@seed-design/react";
import {
type DisplayItemEntry,
type UseAttachmentDisplayReturn,
useAttachmentDisplayContext,
} from "@seed-design/react/primitive";
import * as React from "react";
import { AttachmentDisplayItem, type AttachmentDisplayItemProps } from "./attachment-display-field";
const LABEL_SELECT_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 AttachmentDisplayReorderableProps = {
onTriggerClick: (
helpers: Pick<UseAttachmentDisplayReturn, "addEntries" | "updateEntryStatus">,
) => void;
} & (
| { children: SeedAttachmentDisplay.ContextProps["children"]; onRetry?: never }
| {
children?: undefined;
onRetry?: (
entry: DisplayItemEntry,
helpers: Pick<UseAttachmentDisplayReturn, "updateEntryStatus">,
) => void;
}
);
/**
* @see https://crispy.carrot-soft.tech/react/components/attachment-display-field
*/
export const AttachmentDisplayReorderable = React.forwardRef<
HTMLDivElement,
AttachmentDisplayReorderableProps
>(function AttachmentDisplayReorderable({ onTriggerClick, onRetry, children }, ref) {
const { addEntries, reorderEntry, updateEntryStatus } = useAttachmentDisplayContext();
return (
<DragDropProvider
plugins={(defaults) => [...defaults, autoScrollerPlugin, accessibilityPlugin]}
onDragEnd={({ canceled, operation: { source } }) => {
if (canceled) return;
if (!isSortable(source)) return;
reorderEntry(source.sortable.initialIndex, source.sortable.index);
}}
>
<SeedAttachmentDisplay.Container ref={ref}>
<SeedAttachmentDisplay.Trigger
onClick={() => onTriggerClick({ addEntries, updateEntryStatus })}
aria-label={LABEL_SELECT_FILE}
>
<SeedAttachmentDisplay.TriggerIcon image={<IconCameraFill />} />
<SeedAttachmentDisplay.TriggerItemCount />
</SeedAttachmentDisplay.Trigger>
<SeedAttachmentDisplay.ItemGroup>
<SeedAttachmentDisplay.Context>
{typeof children === "function"
? children
: ({ entries }) =>
entries.map((entry, index) => (
<SortableAttachmentDisplayItem
key={entry.id}
entry={entry}
index={index}
{...(onRetry && { onRetry: () => onRetry(entry, { updateEntryStatus }) })}
/>
))}
</SeedAttachmentDisplay.Context>
</SeedAttachmentDisplay.ItemGroup>
</SeedAttachmentDisplay.Container>
</DragDropProvider>
);
});
AttachmentDisplayReorderable.displayName = "AttachmentDisplayReorderable";
interface SortableAttachmentDisplayItemProps extends AttachmentDisplayItemProps {
index: number;
fileName?: string;
}
export const SortableAttachmentDisplayItem = React.forwardRef<
HTMLLIElement,
SortableAttachmentDisplayItemProps
>(({ entry, index, fileName, ...props }, _ref) => {
const { readOnly } = useAttachmentDisplayContext();
const { ref: sortableRef } = useSortable({
id: entry.id,
index,
disabled: readOnly,
modifiers: [RestrictToHorizontalAxis],
data: { name: fileName ?? `${index + 1}번째 이미지` },
});
return <AttachmentDisplayItem ref={sortableRef} entry={entry} {...props} />;
});
SortableAttachmentDisplayItem.displayName = "SortableAttachmentDisplayItem";
/**
* 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
AttachmentDisplayField
Prop
Type
label?React.ReactNodeindicator?React.ReactNodedescription?React.ReactNodeerrorMessage?React.ReactNodeshowRequiredIndicator?boolean | undefinedentries?DisplayItemEntry[] | undefineddefaultEntries?DisplayItemEntry[] | undefinedonEntriesChange?((entries: DisplayItemEntry[]) => void) | undefinedAttachmentDisplay
Prop
Type
onTriggerClick(helpers: Pick<UseAttachmentDisplayReturn, "addEntries" | "updateEntryStatus">) => voidchildren?((context: UseAttachmentDisplayContext) => React.ReactNode) | undefinedonRetry?((entry: DisplayItemEntry, helpers: Pick<UseAttachmentDisplayReturn, "updateEntryStatus">) => void) | undefinedAttachmentDisplayItem
Prop
Type
onRetry?(() => void) | undefinedentryDisplayItemEntryUsage
Basic usage
Use by combining AttachmentDisplay or AttachmentDisplayReorderable inside AttachmentDisplayField.
AttachmentDisplay does not use HTML <input type="file">. Call an external media picker via onTriggerClick and display the result by passing it to addEntries provided as a callback argument. Since addEntries internally handles maxEntries upper limit and single-mode (maxEntries={1}) substitution, it's safer than directly spreading entries.
Unlike AttachmentField, AttachmentDisplayField does not validate files or directly handle file objects.
import { AttachmentDisplay, AttachmentDisplayField } from "seed-design/ui/attachment-display-field";
<AttachmentDisplayField defaultEntries={[]} maxEntries={10}>
<AttachmentDisplay
onTriggerClick={async ({ addEntries }) => {
const pickedEntries = await openMediaPicker();
addEntries(pickedEntries);
}}
/>
</AttachmentDisplayField>;A controlled approach that directly manages the list with entries and onEntriesChange is also supported. addEntries behaves the same way in this case as well (see Controlled).
Building Items Directly
AttachmentDisplay and AttachmentDisplayReorderable use children as a render prop.
You can use entries to render AttachmentDisplayItem directly. In this case, it's recommended to use the id provided by the DisplayItemEntry type as the key.
If children is not provided, entries is automatically rendered as AttachmentDisplayItem.
import {
AttachmentDisplay,
AttachmentDisplayField,
AttachmentDisplayItem,
} from "seed-design/ui/attachment-display-field";
<AttachmentDisplayField defaultEntries={[]} maxEntries={10}>
<AttachmentDisplay
onTriggerClick={async ({ addEntries }) => {
addEntries(await openMediaPicker());
}}
>
{({ entries }) =>
entries.map((entry) => (
<AttachmentDisplayItem key={entry.id} entry={entry} />
))
}
</AttachmentDisplay>
</AttachmentDisplayField>;Adding Entries
Trigger
AttachmentDisplay provides a layout that includes a trigger (upload button). The onTriggerClick callback runs when the trigger is clicked. It typically calls out to an external media picker. The callback receives { addEntries, updateEntryStatus } as arguments, letting you add the picker results and immediately update the upload status.
import type { DisplayItemEntry } from "@seed-design/react/primitive";
import { AttachmentDisplay, AttachmentDisplayField } from "seed-design/ui/attachment-display-field";
const defaultEntries: DisplayItemEntry[] = [
{
id: "1",
thumbnailUrl: "https://picsum.photos/seed/trigger1/200/200",
status: "success",
},
];
// 외부 미디어 피커 모킹. 실제 환경에서는 네이티브 브릿지/모달/서버 호출 등으로 교체하세요.
async function openMediaPicker(): Promise<DisplayItemEntry[]> {
const id = crypto.randomUUID();
return [
{
id,
thumbnailUrl: `https://picsum.photos/seed/${id}/200/200`,
status: "success",
},
];
}
export default function AttachmentDisplayTrigger() {
return (
<AttachmentDisplayField defaultEntries={defaultEntries} maxEntries={3}>
<AttachmentDisplay
onTriggerClick={async ({ addEntries }) => {
addEntries(await openMediaPicker());
}}
/>
</AttachmentDisplayField>
);
}Listening to Entry Changes
entries is the list of items currently being displayed. You can detect change events for files registered in entries with the onEntriesChange callback.
"use client";
import { Text, VStack } from "@seed-design/react";
import type { DisplayItemEntry } from "@seed-design/react/primitive";
import { useRef, useState } from "react";
import { AttachmentDisplay, AttachmentDisplayField } from "seed-design/ui/attachment-display-field";
// 외부 미디어 피커 모킹. 실제 환경에서는 네이티브 브릿지/모달/서버 호출 등으로 교체하세요.
async function openMediaPicker(): Promise<DisplayItemEntry[]> {
const id = crypto.randomUUID();
return [
{
id,
thumbnailUrl: `https://picsum.photos/seed/${id}/200/200`,
status: "success",
},
];
}
export default function AttachmentDisplayValueChanges() {
const [entries, setEntries] = useState<DisplayItemEntry[]>([]);
const entriesRef = useRef(entries);
const [logs, setLogs] = useState<string[]>([]);
entriesRef.current = entries;
const addLog = (message: string) => {
setLogs((prev) => [...prev, `[${new Date().toLocaleTimeString()}] ${message}`]);
};
// addEntries로 추가하든 제거 버튼으로 지우든 변경은 항상 onEntriesChange로 흐르므로,
// 추가/삭제 감지를 여기 한 곳에서 처리합니다.
const handleEntriesChange = (next: DisplayItemEntry[]) => {
const prev = entriesRef.current;
const added = next.filter((n) => !prev.some((p) => p.id === n.id));
const removed = prev.filter((p) => !next.some((n) => n.id === p.id));
if (added.length > 0) addLog(`added: ${added.map((a) => a.id).join(", ")}`);
if (removed.length > 0) addLog(`removed: ${removed.map((r) => r.id).join(", ")}`);
setEntries(next);
};
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>
<AttachmentDisplayField
entries={entries}
onEntriesChange={handleEntriesChange}
maxEntries={3}
>
<AttachmentDisplay
onTriggerClick={async ({ addEntries }) => {
addEntries(await openMediaPicker());
}}
/>
</AttachmentDisplayField>
</VStack>
);
}Managing Item Status
Each item in entries can have a status of pending, uploading, success, or error. You can freely set the default status of a newly added item to match your intent (uploading for an item an external picker just handed off, success if you're hydrating media that's already been uploaded).
When integrating with an external upload API, use the updateEntryStatus helper, passed along with the onTriggerClick and onRetry callbacks, to update each item's status.
"use client";
import { VStack } from "@seed-design/react";
import type { DisplayItemEntry, DisplayItemStatusDetails } from "@seed-design/react/primitive";
import { AttachmentDisplay, AttachmentDisplayField } from "seed-design/ui/attachment-display-field";
const defaultEntries: DisplayItemEntry[] = [
{
id: "1",
thumbnailUrl: "https://picsum.photos/seed/upload1/200/200",
status: "uploading",
progress: 30,
},
{
id: "2",
thumbnailUrl: "https://picsum.photos/seed/upload2/200/200",
status: "success",
},
{
id: "3",
thumbnailUrl: "https://picsum.photos/seed/upload3/200/200",
status: "error",
},
];
// 외부 미디어 피커 모킹. 실제 환경에서는 네이티브 브릿지/모달/서버 호출 등으로 교체하세요.
async function openMediaPicker(): Promise<DisplayItemEntry[]> {
const id = crypto.randomUUID();
return [
{
id,
thumbnailUrl: `https://picsum.photos/seed/${id}/200/200`,
status: "uploading",
},
];
}
// 실제 환경에서는 네이티브 브릿지 또는 외부 업로드 API와 연동하세요.
// status는 컴포넌트가 콜백으로 전달하는 updateEntryStatus 헬퍼로만 갱신합니다.
function simulateUpload(
id: string,
updateEntryStatus: (id: string, details: DisplayItemStatusDetails) => void,
) {
updateEntryStatus(id, { status: "uploading", progress: 0 });
let progress = 0;
const interval = setInterval(() => {
progress += 20;
if (progress >= 100) {
clearInterval(interval);
updateEntryStatus(id, Math.random() > 0.5 ? { status: "success" } : { status: "error" });
} else {
updateEntryStatus(id, { status: "uploading", progress });
}
}, 300);
}
export default function AttachmentDisplayStatus() {
return (
<VStack gap="x4" p="x6" width="100%">
<AttachmentDisplayField defaultEntries={defaultEntries} maxEntries={5}>
<AttachmentDisplay
onTriggerClick={async ({ addEntries, updateEntryStatus }) => {
const pickedEntries = await openMediaPicker();
addEntries(pickedEntries);
for (const entry of pickedEntries) {
simulateUpload(entry.id, updateEntryStatus);
}
}}
onRetry={(entry, { updateEntryStatus }) => simulateUpload(entry.id, updateEntryStatus)}
/>
</AttachmentDisplayField>
</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 onAttachmentDisplayruns with(entry, { updateEntryStatus })as arguments. UseupdateEntryStatusto set that item back touploadingto retry the upload.
- When clicked, the
Reordering Entries
Using AttachmentDisplayReorderable lets you change the order of items by dragging.
This component is provided as a separate snippet, ui:attachment-display-field-reorderable, to keep the dnd-kit dependency isolated.
Since reorderEntry 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.
"use client";
import type { DisplayItemEntry } from "@seed-design/react/primitive";
import { useState } from "react";
import { AttachmentDisplayField } from "seed-design/ui/attachment-display-field";
import { AttachmentDisplayReorderable } from "seed-design/ui/attachment-display-field-reorderable";
const defaultEntries: DisplayItemEntry[] = [
{ id: "1", thumbnailUrl: "https://picsum.photos/seed/reorder1/200/200", status: "success" },
{ id: "2", thumbnailUrl: "https://picsum.photos/seed/reorder2/200/200", status: "success" },
{ id: "3", thumbnailUrl: "https://picsum.photos/seed/reorder3/200/200", status: "success" },
];
// 외부 미디어 피커 모킹. 실제 환경에서는 네이티브 브릿지/모달/서버 호출 등으로 교체하세요.
async function openMediaPicker(): Promise<DisplayItemEntry[]> {
const id = crypto.randomUUID();
return [
{
id,
thumbnailUrl: `https://picsum.photos/seed/${id}/200/200`,
status: "success",
},
];
}
export default function AttachmentDisplayReorderableExample() {
const [entries, setEntries] = useState<DisplayItemEntry[]>(defaultEntries);
return (
<AttachmentDisplayField entries={entries} onEntriesChange={setEntries} maxEntries={5}>
<AttachmentDisplayReorderable
onTriggerClick={async ({ addEntries }) => {
addEntries(await openMediaPicker());
}}
/>
</AttachmentDisplayField>
);
}Examples
Disabled
You can disable the trigger button with the disabled prop.
import { VStack } from "@seed-design/react";
import type { DisplayItemEntry } from "@seed-design/react/primitive";
import { AttachmentDisplay, AttachmentDisplayField } from "seed-design/ui/attachment-display-field";
const sampleEntries: DisplayItemEntry[] = [
{
id: "1",
thumbnailUrl: "https://picsum.photos/seed/disabled1/200/200",
status: "success",
},
];
export default function AttachmentDisplayDisabled() {
return (
<VStack gap="x4" p="x6" width="100%">
<AttachmentDisplayField defaultEntries={sampleEntries} maxEntries={5} disabled>
<AttachmentDisplay onTriggerClick={() => {}} />
</AttachmentDisplayField>
</VStack>
);
}Read Only
You can express a read-only state with the readOnly prop. The trigger, the file remove button, and reordering are all disabled.
import { VStack } from "@seed-design/react";
import type { DisplayItemEntry } from "@seed-design/react/primitive";
import { AttachmentDisplay, AttachmentDisplayField } from "seed-design/ui/attachment-display-field";
const sampleEntries: DisplayItemEntry[] = [
{
id: "1",
thumbnailUrl: "https://picsum.photos/seed/readonly1/200/200",
status: "success",
},
{
id: "2",
thumbnailUrl: "https://picsum.photos/seed/readonly2/200/200",
status: "success",
},
];
export default function AttachmentDisplayReadOnly() {
return (
<VStack gap="x4" p="x6" width="100%">
<AttachmentDisplayField defaultEntries={sampleEntries} maxEntries={5} readOnly>
<AttachmentDisplay onTriggerClick={() => {}} />
</AttachmentDisplayField>
</VStack>
);
}Controlled
You can control the item list externally using entries and onEntriesChange.
"use client";
import { HStack, Text, VStack } from "@seed-design/react";
import type { DisplayItemEntry } from "@seed-design/react/primitive";
import { useState } from "react";
import { ActionButton } from "seed-design/ui/action-button";
import { AttachmentDisplay, AttachmentDisplayField } from "seed-design/ui/attachment-display-field";
// 외부 미디어 피커 모킹. 실제 환경에서는 네이티브 브릿지/모달/서버 호출 등으로 교체하세요.
async function openMediaPicker(): Promise<DisplayItemEntry[]> {
const id = crypto.randomUUID();
return [
{
id,
thumbnailUrl: `https://picsum.photos/seed/${id}/200/200`,
status: "success",
},
];
}
export default function AttachmentDisplayControlled() {
const [entries, setEntries] = useState<DisplayItemEntry[]>([]);
return (
<VStack gap="x4" p="x6" width="100%">
<AttachmentDisplayField entries={entries} onEntriesChange={setEntries} maxEntries={5}>
<AttachmentDisplay
onTriggerClick={async ({ addEntries }) => {
addEntries(await openMediaPicker());
}}
/>
</AttachmentDisplayField>
<Text>현재 아이템: {entries.length}개</Text>
<HStack gap="x2">
<ActionButton type="button" variant="neutralWeak" onClick={() => setEntries([])}>
전체 삭제
</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 { vars } from "@seed-design/css/vars";
import { VStack } from "@seed-design/react";
import type { DisplayItemEntry } from "@seed-design/react/primitive";
import { AttachmentDisplay, AttachmentDisplayField } from "seed-design/ui/attachment-display-field";
import { TextField, TextFieldInput } from "seed-design/ui/text-field";
const defaultEntries: DisplayItemEntry[] = Array.from({ length: 8 }, (_, i) => ({
id: String(i + 1),
thumbnailUrl: `https://picsum.photos/seed/inset${i + 1}/200/200`,
status: "success",
}));
export default function AttachmentDisplayCustomInset() {
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>
<AttachmentDisplayField
defaultEntries={defaultEntries}
maxEntries={10}
style={
{
"--seed-attachment-input-extend-x": vars.$dimension.spacingX.globalGutter,
} as React.CSSProperties
}
>
<AttachmentDisplay
onTriggerClick={() => {
// 외부 미디어 피커 호출 자리
}}
/>
</AttachmentDisplayField>
</VStack>
</VStack>
);
}Field Integration
You can pass Field-related props such as label, description, and errorMessage.
"use client";
import { VStack } from "@seed-design/react";
import type { DisplayItemEntry } from "@seed-design/react/primitive";
import { useState } from "react";
import { AttachmentDisplay, AttachmentDisplayField } from "seed-design/ui/attachment-display-field";
const defaultEntries: DisplayItemEntry[] = [
{ id: "1", thumbnailUrl: "https://picsum.photos/seed/field1/200/200", status: "success" },
];
// 외부 미디어 피커 모킹. 실제 환경에서는 네이티브 브릿지/모달/서버 호출 등으로 교체하세요.
async function openMediaPicker(): Promise<DisplayItemEntry[]> {
const id = crypto.randomUUID();
return [
{
id,
thumbnailUrl: `https://picsum.photos/seed/${id}/200/200`,
status: "success",
},
];
}
export default function AttachmentDisplayFieldExample() {
const [entries, setEntries] = useState<DisplayItemEntry[]>(defaultEntries);
const invalid = entries.length < 1;
return (
<VStack gap="x4" p="x6" width="100%">
<AttachmentDisplayField
entries={entries}
onEntriesChange={setEntries}
maxEntries={5}
invalid={invalid}
label="프로필 사진"
indicator="선택"
description="최대 5장까지 첨부할 수 있어요"
errorMessage="최소 1장은 첨부해야 해요"
showRequiredIndicator
>
<AttachmentDisplay
onTriggerClick={async ({ addEntries }) => {
addEntries(await openMediaPicker());
}}
/>
</AttachmentDisplayField>
</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 AttachmentDisplay.ItemBadge provided by @seed-design/react.
In the example below, AttachmentDisplay.ItemBadge is used to show a "Main photo" badge on the first image.
"use client";
import { IconArrowClockwiseCircularFill, IconXmarkFill } from "@karrotmarket/react-monochrome-icon";
import { AttachmentDisplay as SeedAttachmentDisplay, Icon, VStack } from "@seed-design/react";
import type { DisplayItemEntry } from "@seed-design/react/primitive";
import { AttachmentDisplay, AttachmentDisplayField } from "seed-design/ui/attachment-display-field";
import { ProgressCircle } from "seed-design/ui/progress-circle";
const LABEL_REMOVE = "삭제";
const LABEL_RETRY = "재시도";
function CustomImageItem({
entry,
isCover,
onRetry,
}: {
entry: DisplayItemEntry;
isCover?: boolean;
onRetry?: () => void;
}) {
return (
<SeedAttachmentDisplay.Item entry={entry}>
<SeedAttachmentDisplay.ItemImage />
{isCover && <SeedAttachmentDisplay.ItemBadge>대표사진</SeedAttachmentDisplay.ItemBadge>}
<SeedAttachmentDisplay.ItemBackdrop status="uploading">
{(e) => (
<ProgressCircle
size="24"
tone="staticWhite"
{...("progress" in e && { value: e.progress })}
/>
)}
</SeedAttachmentDisplay.ItemBackdrop>
{onRetry && (
<SeedAttachmentDisplay.ItemBackdrop status="error">
<SeedAttachmentDisplay.ItemActionButton onClick={onRetry}>
<Icon svg={<IconArrowClockwiseCircularFill />} />
{LABEL_RETRY}
</SeedAttachmentDisplay.ItemActionButton>
</SeedAttachmentDisplay.ItemBackdrop>
)}
<SeedAttachmentDisplay.ItemRemoveButton aria-label={LABEL_REMOVE}>
<Icon svg={<IconXmarkFill />} />
</SeedAttachmentDisplay.ItemRemoveButton>
</SeedAttachmentDisplay.Item>
);
}
const defaultEntries: DisplayItemEntry[] = [
{ id: "1", thumbnailUrl: "https://picsum.photos/seed/customizing1/200/200", status: "success" },
{ id: "2", thumbnailUrl: "https://picsum.photos/seed/customizing2/200/200", status: "success" },
{ id: "3", thumbnailUrl: "https://picsum.photos/seed/customizing3/200/200", status: "success" },
];
export default function AttachmentDisplayCustomizingItems() {
return (
<VStack gap="x4" p="x6" width="100%">
<AttachmentDisplayField defaultEntries={defaultEntries} maxEntries={10}>
<AttachmentDisplay
onTriggerClick={() => {
// 외부 미디어 피커 호출 자리
}}
>
{({ entries }) =>
entries.map((entry, index) => (
<CustomImageItem key={entry.id} entry={entry} isCover={index === 0} />
))
}
</AttachmentDisplay>
</AttachmentDisplayField>
</VStack>
);
}Attachment Display Field vs. Attachment Field
Use AttachmentField when you need to use the HTML <input type="file">, and use AttachmentDisplayField when you need to display media based on URLs by integrating with an external source.
| Attachment Field | Attachment Display | |
|---|---|---|
| Media source | HTML <input type="file"> | Image URL |
| Data model | File-based FileEntry | URL-based DisplayItemEntry |
| File selection | <input type="file"> | Not handled (delegated to onTriggerClick) |
| Upload via drag and drop | AttachmentDropzone | Not handled |
| File validation | accept, maxFileSize, etc. | Not handled |
| Form integration | <input type="file"> sync | Not handled |