# Attachment Field URL: /react/components/attachment-field Source: https://github.com/daangn/seed-design/blob/dev/docs/content/react/components/attachment-field.mdx A component where you can select files or upload via drag and drop. 사용 가능 버전: @seed-design/react@2.0.0, @seed-design/css@2.0.0 ## Preview ```tsx import { VStack } from "@seed-design/react"; import { AttachmentField, AttachmentInput } from "seed-design/ui/attachment-field"; export default function AttachmentFieldPreview() { return ( ); } ``` ## Installation ### Default Includes components that can be used when reordering files is not needed. - npm: npx @seed-design/cli@latest add ui:attachment-field - pnpm: pnpm dlx @seed-design/cli@latest add ui:attachment-field - yarn: yarn dlx @seed-design/cli@latest add ui:attachment-field - bun: bun x @seed-design/cli@latest add ui:attachment-field ### Reorderable Includes components that can be used when reordering files via drag and drop is needed. The [dnd-kit](https://dndkit.com/overview) dependency is added to the project. - npm: npx @seed-design/cli@latest add ui:attachment-field-reorderable - pnpm: pnpm dlx @seed-design/cli@latest add ui:attachment-field-reorderable - yarn: yarn dlx @seed-design/cli@latest add ui:attachment-field-reorderable - bun: bun x @seed-design/cli@latest add ui:attachment-field-reorderable ## Props ### `AttachmentField` ### `AttachmentInput` ### `AttachmentDropzone` ### `AttachmentInputItem` ## Usage ### Basic usage Use by combining one of `AttachmentInput`, `AttachmentDropzone`, `AttachmentInputReorderable`, or `AttachmentDropzoneReorderable` inside `AttachmentField`. ```tsx import { AttachmentField, AttachmentInput, AttachmentDropzone, } from "seed-design/ui/attachment-field"; ; ; ``` ```tsx import { AttachmentField } from "seed-design/ui/attachment-field"; import { AttachmentInputReorderable, AttachmentDropzoneReorderable, } from "seed-design/ui/attachment-field-reorderable"; ; ; ``` ### 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`. ```tsx import { AttachmentField, AttachmentInput, AttachmentInputItem, } from "seed-design/ui/attachment-field"; {({ acceptedFileEntries }) => acceptedFileEntries.map((entry) => ( )) } ; ``` ## Uploading Files ### Trigger Using `AttachmentInput` lets you use a layout that includes a trigger (upload button). ```tsx 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 ( ); } ``` ### Dropzone Using `AttachmentDropzone` lets you use a layout that includes a drag-and-drop area. ```tsx 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 ( ); } ``` ### 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. ```tsx 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([]); const addLog = (message: string) => { setLogs((prev) => [...prev, `[${new Date().toLocaleTimeString()}] ${message}`]); }; return ( {logs.length === 0 ? ( 파일을 추가하거나 삭제하면 로그가 표시됩니다. ) : ( logs.map((log, index) => ( {log} )) )} { 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(", ")}`, ); }} > {({ acceptedFileEntries }) => acceptedFileEntries.map((fileEntry) => ( )) } ); } ``` ## 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"`. ```tsx 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 ( ); } ``` ### 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 `` 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. ```tsx 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(); return ( setErrorMessage(undefined)} onFileReject={(files) => { const messages = files.map( ({ file, errors }) => `"${file.name}": ${errors.map(getErrorMessage).join(", ")}`, ); setErrorMessage(messages.join("\n")); }} > ); } ``` ### File Size You can use the `minFileSize` and `maxFileSize` props. - If a file the user selected is smaller than `minFileSize`, the `onFileReject` callback runs with a `"FILE_TOO_SMALL"` error. - If a file the user selected is larger than `maxFileSize`, the `onFileReject` callback runs with a `"FILE_TOO_LARGE"` error. ```tsx 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(); return ( setErrorMessage(undefined)} onFileReject={(files) => { const messages = files.map( ({ file, errors }) => `"${file.name}": ${errors.map(getErrorMessage).join(", ")}`, ); setErrorMessage(messages.join("\n")); }} > ); } ``` ### 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`. ```tsx 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(); return ( 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자를 초과합니다.`); }} > ); } ``` ## 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. ```tsx 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 ( { for (const entry of entries) { startUpload(entry.file, entry.id, updateFileEntryStatus); } }} > {({ acceptedFileEntries, updateFileEntryStatus }) => acceptedFileEntries.map((fileEntry) => ( startUpload(fileEntry.file, fileEntry.id, updateFileEntryStatus)} /> )) } ); } ``` - `uploading`: A [ProgressCircle](/react/components/progress-circle) is shown. - You can set `progress` to display the upload progress. - If `progress` is not set, it's shown in the [indeterminate](/react/components/progress-circle#indeterminate) state. - `error`: A retry button is shown. - When clicked, the `onRetry` callback set on `AttachmentInputItem` runs. 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`](#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. ```tsx 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 ( ); } ``` ## 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"]`. ```tsx import { VStack } from "@seed-design/react"; import { AttachmentField, AttachmentInput } from "seed-design/ui/attachment-field"; export default function AttachmentFieldAcceptImage() { return ( ); } ``` For some image formats such as [`"image/heic"`](https://caniuse.com/heif), 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 `` as `disabled` so its value is not sent when the form is submitted. ```tsx 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 ( ); } ``` ### 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 `` is preserved and sent along when the form is submitted. ```tsx 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 ( ); } ``` ### Controlled You can control the file list externally using `acceptedFileEntries` and `onAcceptedFileEntriesChange`. ```tsx 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([]); return ( 현재 파일: {JSON.stringify(acceptedFileEntries.map((f) => f.file.name))} setAcceptedFileEntries([])} > 전체 삭제 ); } ``` ### Custom Inset You can use the `--seed-attachment-input-extend-x` CSS variable to configure the scrolling item list to extend beyond the layout. ```tsx 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 ( ({ id: `${index}`, file, status: "pending", }))} rootProps={{ style: { "--seed-attachment-input-extend-x": vars.$dimension.spacingX.globalGutter, } as React.CSSProperties, }} > ); } ``` ### Field Integration You can use Field-related props such as `label`, `description`, and `errorMessage`. ```tsx import { Divider, VStack } from "@seed-design/react"; import { AttachmentField, AttachmentInput } from "seed-design/ui/attachment-field"; export default function AttachmentFieldField() { return ( ); } ``` ### Form (Uncontrolled) Files registered in `acceptedFileEntries` are synced to the `files` of ``, so you can use `
` and the `name` prop to include them in the formData. ```tsx 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({}); const handleSubmit = (event: FormEvent) => { 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 ( { if (files.length > 0) { setFieldErrors({}); } }} {...(fieldErrors.files && { invalid: true, errorMessage: fieldErrors.files })} > 제출 ); } ``` ### React Hook Form ```tsx 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({ 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 ( 초기화 제출 ); } ``` ### 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. ```tsx "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 ( {isCover && 대표사진} {(entry) => ( )} {onRetry && ( } /> {LABEL_RETRY} )} } /> ); } export default function AttachmentFieldCustomizingItems() { return ( {({ acceptedFileEntries }) => acceptedFileEntries.map((fileEntry, index) => ( )) } ); } ```