프리뷰 또는 이전 버전의 문서를 보고 있습니다.seed-design.io 방문
우리는 왜 디자인 엔지니어를 찾게 됐을까
Skip to Content
React

Attachment Field

파일을 선택하거나 드래그 앤 드롭으로 업로드할 수 있는 컴포넌트입니다.

사용 가능 버전@seed-design/react@2.0.0, @seed-design/css@2.0.0

    Installation

    Default

    파일 순서 변경이 불필요한 경우 사용할 수 있는 컴포넌트를 포함합니다.

    npx @seed-design/cli@latest add ui:attachment-field

    Reorderable

    드래그 앤 드롭을 통한 파일 순서 변경이 필요한 경우 활용할 수 있는 컴포넌트를 포함합니다. 프로젝트에 dnd-kit 의존성이 추가됩니다.

    npx @seed-design/cli@latest add ui:attachment-field-reorderable

    Props

    AttachmentField

    Prop

    Type

    label?React.ReactNode
    labelWeight?"bold" | "medium" | undefined

    Default

    "medium"

    indicator?React.ReactNode
    description?React.ReactNode
    errorMessage?React.ReactNode
    showRequiredIndicator?boolean | undefined
    inputProps?React.InputHTMLAttributes<HTMLInputElement> | undefined
    fieldRef?React.Ref<HTMLDivElement> | undefined
    rootProps?React.HTMLAttributes<HTMLDivElement> | undefined
    extendSafeAreaX?boolean | undefined

    Default

    false

    acceptedFileEntries?AttachmentInputFileEntry[] | undefined
    defaultAcceptedFileEntries?AttachmentInputFileEntry[] | undefined
    onAcceptedFileEntriesChange?((fileEntries: AttachmentInputFileEntry[]) => void) | undefined
    onFileReject?((rejections: FileRejection[]) => void) | undefined
    onFileAccept?((acceptedEntries: AttachmentInputFileEntry[], helpers: { updateFileEntryStatus: (id: string, details: FileStatusDetails) => void; }) => void) | undefined
    accept?string | string[] | undefined

    Accepted file types (e.g., "image/*", ".pdf", "image/png")

    disabled?boolean | undefined

    Default

    false

    required?boolean | undefined

    Default

    false

    invalid?boolean | undefined

    Default

    false

    readOnly?boolean | undefined

    Default

    false

    maxFiles?number | undefined

    Default

    1

    maxFileSize?number | undefined

    Default

    Infinity

    minFileSize?number | undefined

    Default

    0

    name?string | undefined
    validate?((file: File) => FileError[] | null) | undefined

    Custom validation function.

    preventDocumentDrop?boolean | undefined

    Whether to prevent the browser's default behavior when files are dropped outside the dropzone (e.g., opening the file in a new tab).

    Default

    true

    AttachmentInput

    Prop

    Type

    children?((context: AttachmentInputContextValue) => React.ReactNode) | undefined
    onRetry?((fileEntry: AttachmentInputFileEntry, helpers: Pick<AttachmentInputContextValue, "updateFileEntryStatus">) => void) | undefined

    AttachmentDropzone

    Prop

    Type

    children?((context: AttachmentInputContextValue) => React.ReactNode) | undefined
    onRetry?((fileEntry: AttachmentInputFileEntry, helpers: Pick<AttachmentInputContextValue, "updateFileEntryStatus">) => void) | undefined

    AttachmentInputItem

    Prop

    Type

    onRetry?(() => void) | undefined
    reorderHandle?React.ReactNode

    Rendered before the item contents. Pass an AttachmentInput.ItemReorderHandle to make the item reorderable.

    type?"general" | "image" | undefined

    Default

    "general"

    fileEntryAttachmentInputFileEntry
    dragging?boolean | undefined

    Shows the item in its dragging state. Pass the drag state from your drag and drop library while the item is being reordered.

    Default

    false

    Usage

    기본 사용법

    AttachmentField 안에 AttachmentInput, AttachmentDropzone, AttachmentInputReorderable, AttachmentDropzoneReorderable 중 하나를 조합하여 사용합니다.

    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>;

    Item 직접 구성하기

    AttachmentInput, AttachmentDropzone, AttachmentInputReorderable, AttachmentDropzoneReorderable은 children을 render prop으로 사용합니다.

    acceptedFileEntries을 활용하여 AttachmentInputItem을 직접 렌더링할 수 있습니다. 이때 FileEntry 타입이 제공하는 id를 key로 활용하는 것을 권장합니다.

    children을 제공하지 않는 경우 자동으로 acceptedFileEntries에 등록된 파일을 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

    AttachmentInput를 사용하면 trigger(업로드 버튼)가 포함된 레이아웃을 사용할 수 있습니다.

    Dropzone

    AttachmentDropzone을 사용하면 드래그 앤 드롭 영역이 포함된 레이아웃을 사용할 수 있습니다.

    또는 여기로 드래그해서 업로드

    Listening to Accepted File Changes

    acceptedFileEntries는 유효성 검사를 마친 파일의 목록입니다. onAcceptedFileEntriesChange 콜백으로 acceptedFileEntries에 등록된 파일 변경 이벤트를 감지할 수 있습니다.

    파일을 추가하거나 삭제하면 로그가 표시됩니다.

      Validating Files

      사용자가 선택한 파일이 acceptedFileEntries에 등록되기 전 유효성을 확인할 수 있습니다.

      유효하지 않은 파일에 대해 각각 onFileReject 콜백이 실행됩니다. 해당 콜백에서 파일과 에러 코드들을 확인하여 에러 메시지를 표시할 수 있습니다.

      Max Files

      maxFiles로 업로드 가능한 최대 파일 수를 제한할 수 있습니다. 기본값은 1입니다. 최대 수에 도달한 경우 trigger 및 dropzone이 비활성화됩니다.

      업로드 가능한 파일의 수보다 많은 파일을 선택한 경우 업로드 가능한 파일까지 acceptedFileEntries에 등록됩니다. 나머지 파일에 대해서는 각각 onFileReject 콜백이 실행됩니다. 이때 reject된 파일의 에러는 "TOO_MANY_FILES"입니다.

      Invalid File Type

      accept로 업로드 가능한 파일의 종류를 제한할 수 있습니다.

      MIME type(image/png, image/*) 또는 확장자(.png, .jpg, .jpeg) 형식을 지정할 수 있으며, string[]을 전달하는 경우 각 string ,로 join합니다.

      <input type="file">에 등록되는 accept 속성을 통해 사용자가 선택할 수 있는 파일의 종류를 제한하는 것은 브라우저 UI에서만 동작하는 편의 기능입니다. 따라서 사용자는 브라우저 파일 선택 다이얼로그의 모든 파일 보기와 같은 기능을 통해 제한된 종류의 파일도 선택할 수 있습니다. 이렇게 선택된 파일의 경우 "INVALID_TYPE" 에러와 함께 onFileReject 콜백이 실행됩니다.

      파일 종류 검증이 필요한 경우 해당 검증은 서버에서도 수행되어야 합니다.

        File Size

        minFileSize, maxFileSize prop을 활용할 수 있습니다.

        • 사용자가 선택한 파일이 minFileSize보다 작은 경우 "FILE_TOO_SMALL" 에러와 함께 onFileReject 콜백이 실행됩니다.
        • 사용자가 선택한 파일이 maxFileSize보다 큰 경우 "FILE_TOO_LARGE" 에러와 함께 onFileReject 콜백이 실행됩니다.

          Custom Validation

          validate prop으로 각 파일에 대한 유효성 검사를 직접 추가할 수 있습니다. 커스텀 에러 코드를 반환하여 onFileReject에서 에러 종류별로 메시지를 분기할 수 있습니다.

            Managing File Status

            acceptedFileEntries의 각 항목은 pending, uploading, success, error의 status를 가질 수 있습니다. 새로 추가되는 항목의 status 기본값은 pending입니다.

            파일 선택 직후 외부 업로드 API와 연동하는 경우, 사용자에게 각 파일 항목의 업로딩 상태를 보여줄 수 있습니다. onFileAccept 콜백에서 새로 추가된 파일을 받고, 함께 제공되는 updateFileEntryStatus 헬퍼를 사용하여 항목의 status를 업데이트합니다.

              • uploading: ProgressCircle이 표시됩니다.
                • progress를 설정하여 업로드 진행률을 표시할 수 있습니다.
                • progress를 지정하지 않는 경우 indeterminate 상태로 표시됩니다.
              • error: 재시도 버튼이 표시됩니다.
                • 클릭 시 AttachmentInputItem에 지정한 onRetry 콜백이 실행됩니다.

              유효성 검증에 성공한 파일 항목은 status와 관계없이 acceptedFileEntries에 유지되므로, 네이티브 form 제출 시 포함됩니다.

              Reordering Files

              AttachmentInputReorderable 또는 AttachmentDropzoneReorderable을 사용하면 드래그로 파일의 순서를 변경할 수 있습니다.

              두 컴포넌트는 dnd-kit 의존성 분리를 위해 별도 snippet ui:attachment-field-reorderable로 제공됩니다.

              Context를 통해 reorderFileEntry가 제공되므로, 필요한 경우 원하는 드래그 앤 드롭 동작을 직접 구현하거나, 이미 프로젝트에서 사용 중인 드래그 앤 드롭 라이브러리와 연동하여 사용할 수 있습니다.

              snippet의 SortableAttachmentInputItem은 항목마다 순서 변경 버튼인 AttachmentInput.ItemReorderHandle을 렌더링합니다. 항목 자체는 목록 항목으로 남으므로 스크린 리더와 키보드에서 순서 변경 버튼과 제거 버튼을 따로 탐색할 수 있습니다. 다른 라이브러리와 연동할 때도 AttachmentInput.ItemReorderHandle에 라이브러리의 handle ref와 aria-label을 연결하고, 드래그 중인 항목에는 dragging을 전달하세요.

              Examples

              Showing Thumbnails

              파일 이름 및 크기 대신 이미지 미리보기를 표시하려면 accept를 "image/*", ["image/png", "image/jpeg"] 등으로 설정하여 사용자가 이미지 파일만 선택할 수 있도록 제한합니다.

                "image/heic" 등 일부 이미지 형식은 브라우저에 따라 이미지 미리보기가 표시되지 않을 수 있습니다.

                Disabled

                disabled prop으로 trigger 및 dropzone을 비활성화하여 신규 파일 선택을 차단하고, <input type="file">을 disabled 처리하여 폼 제출 시 값이 전송되지 않도록 합니다.

                Read Only

                readOnly prop으로 첨부된 파일을 읽기 전용 상태로 표시할 수 있습니다. trigger, dropzone, 파일 제거 버튼, 순서 변경 모두 비활성화되지만 <input type="file">의 값은 유지되어 form 제출 시 함께 전송됩니다.

                Controlled

                acceptedFileEntries와 onAcceptedFileEntriesChange를 사용하여 외부에서 파일 목록을 제어할 수 있습니다.

                  현재 파일: []

                  Custom Inset

                  --seed-attachment-input-extend-x CSS 변수를 사용하여 스크롤되는 아이템 목록이 레이아웃 바깥으로 빠져나오도록 구성할 수 있습니다.

                  extendSafeAreaX를 함께 지정하면 목록이 --seed-attachment-input-extend-x에 좌우 safe area inset을 더한 만큼 넓어져 화면 끝까지 스크롤되고, 첫 항목과 마지막 항목은 safe area 안에 남습니다. AppScreenContent처럼 inset을 반영한 컨테이너 안에서 사용하세요. 화면 끝까지 채우는 다른 방법은 Safe Area 구현 가이드를 참고하세요.

                  Field Integration

                  label, description, errorMessage 등의 Field 관련 prop을 사용할 수 있습니다.


                      Form (Uncontrolled)

                      acceptedFileEntries에 등록된 파일이 <input type="file">의 files로 동기화되므로 <form>과 name prop을 사용하여 formData에 포함시킬 수 있습니다.

                        React Hook Form

                          Customizing Items

                          Snippet이 제공하는 기본 아이템 구성 외에 추가적인 커스터마이징이 필요한 경우, @seed-design/react에서 제공하는 AttachmentInput.ItemBadge 등의 요소를 활용하여 직접 아이템을 구성할 수 있습니다.

                          아래 예시에서는 AttachmentInput.ItemBadge를 사용하여 첫 번째 이미지에 "대표사진" 배지를 표시합니다.

                            Video Duration

                            AttachmentInputItemDurationBadge는 동영상의 재생시간을 이미지 아이템의 왼쪽 위에 표시합니다. seconds에 초 단위 재생시간을 넘기면 1시간 미만은 2:05, 1시간 이상은 1:02:05 형식으로 표시합니다. 초 미만은 버리고, 24시간을 넘어도 시간 단위로 누적합니다.

                            스크린리더에는 "재생시간 1시간 2분 5초" 같은 문구를 aria-label로 제공합니다. 다른 문구가 필요하면 aria-label을 직접 넘기세요. 포맷은 ui:attachment-field와 함께 설치되는 lib:format-duration이 처리합니다.

                            accept에 video/*가 포함되면 아이템이 기본적으로 파일 레이아웃으로 표시됩니다. 동영상을 썸네일로 보여 주려면 AttachmentInput.Item에 type="image"를 넘겨 이미지 레이아웃으로 바꾸세요. 이미지 레이아웃에서 AttachmentInput.ItemImage는 사진의 미리보기를 자동으로 렌더링하지만, 동영상은 썸네일 URL을 src로 직접 넘겨야 합니다. 아래 예시는 <video>의 메타데이터와 canvas로 썸네일과 재생시간을 구합니다.

                              Extending to Safe Area

                              AttachmentField에 extendSafeAreaX를 지정하면 첨부 목록의 스크롤 영역이 좌우 inset까지 넓어집니다. label·description과 처음·마지막 항목에 필요한 여백은 유지합니다. inset을 반영한 컨테이너 안에서 사용하세요.

                              아래 예제는 좌우에 가상의 inset을 적용합니다. 붉은 빗금은 콘텐츠를 피해야 하는 inset 영역이며, 두 경계선 사이는 안전 영역입니다. 스위치로 확장 전(AS IS)과 확장 후(TO BE)를 비교하고, 배경·스크롤 영역의 경계와 콘텐츠 위치를 확인하세요. 같은 버전에서 옵션을 끄고 켠 비교입니다.

                              비교용 inset: 왼쪽 24px · 오른쪽 48px (가상)

                              붉은 빗금은 콘텐츠를 피해야 하는 inset 영역이며, 두 경계선 사이는 안전 영역입니다.

                              확장 전 (AS IS) · extendSafeAreaX=false

                              Last updated on 2026. 11. 27.