메인 콘텐츠로 건너뛰기

반환 값 레퍼런스

useDropup 훅이 반환하는 모든 것입니다.

개요

const {
files, // 파일 객체 배열
state, // 현재 상태
actions, // 사용 가능한 액션
getDropProps, // 드롭 영역용 props
getInputProps, // input 요소용 props
openFileDialog, // 파일 선택기 열기
} = useDropup();

files

추가된 모든 파일을 나타내는 DropupFile 객체의 배열입니다.

const { files } = useDropup();

files.forEach(file => {
console.log(file.id); // "abc123"
console.log(file.name); // "photo.jpg"
console.log(file.size); // 1234567
console.log(file.type); // "image/jpeg"
console.log(file.status); // "idle" | "uploading" | "complete" | "error"
console.log(file.progress); // 0-100
console.log(file.preview); // "blob:http://..." (이미지만)
console.log(file.uploadedUrl); // "https://..." (업로드 후)
console.log(file.error); // DropupError (실패 시)
});

DropupFile 속성

속성타입설명
idstring고유 식별자
fileFile원본 브라우저 File 객체
namestring파일 이름
sizenumber바이트 단위 크기
typestringMIME 타입
statusFileStatus현재 상태
progressnumber업로드 진행률 (0-100)
previewstring | undefined이미지용 미리보기 URL
uploadedUrlstring | undefined업로드 성공 후 URL
responseunknown서버 응답 데이터
errorDropupError | undefined업로드 실패 시 오류
metaRecord<string, unknown>커스텀 메타데이터

FileStatus 값

상태설명
'idle'파일 추가됨, 업로드 중 아님
'uploading'업로드 진행 중
'complete'업로드 성공
'error'업로드 실패
'paused'업로드 일시 중지됨 (재개 가능한 업로드)

state

드롭 영역의 현재 상태입니다.

const { state } = useDropup();

console.log(state.isDragging); // 드래그 중일 때 true
console.log(state.isDragAccept); // 드래그된 파일이 유효할 때 true
console.log(state.isDragReject); // 드래그된 파일이 무효할 때 true
console.log(state.isUploading); // 파일 업로드 중일 때 true
console.log(state.progress); // 전체 진행률 0-100
console.log(state.status); // 'idle' | 'uploading' | 'complete' | 'error'

State 속성

속성타입설명
isDraggingboolean파일이 드롭 영역 위에서 드래그 중
isDragAcceptboolean드래그된 파일이 유효성 검사 통과
isDragRejectboolean드래그된 파일이 유효성 검사 실패
isUploadingboolean현재 업로드 중인 파일 있음
progressnumber모든 파일의 평균 진행률 (0-100)
statusDropupStatus전체 업로드 상태

DropupStatus 값

상태설명
'idle'진행 중인 업로드 없음
'uploading'하나 이상의 파일 업로드 중
'complete'모든 업로드 성공적으로 완료
'error'하나 이상의 업로드 실패

actions

사용 가능한 모든 액션을 포함하는 객체입니다.

const { actions } = useDropup();

// 업로드 시작
actions.upload(); // 모든 idle 파일 업로드
actions.upload(['id1', 'id2']); // 특정 파일 업로드

// 업로드 취소
actions.cancel(); // 모든 업로드 취소
actions.cancel('file-id'); // 특정 파일 취소

// 파일 제거
actions.remove('file-id'); // 특정 파일 제거
actions.reset(); // 모든 파일 제거

// 실패한 업로드 재시도
actions.retry(); // 모든 실패한 것 재시도
actions.retry(['id1']); // 특정 파일 재시도

// 프로그래밍 방식으로 파일 추가
actions.addFiles(fileList); // File[] 또는 FileList 추가

// 파일 메타데이터 업데이트
actions.updateFileMeta('file-id', { tag: 'important' });

액션 메서드

upload(fileIds?)

파일 업로드 시작.

// 모든 idle 파일 업로드
actions.upload();

// 특정 파일 업로드
actions.upload(['file-id-1', 'file-id-2']);
매개변수타입설명
fileIdsstring[] (선택사항)업로드할 특정 파일 ID

cancel(fileId?)

진행 중인 업로드 취소.

// 모든 업로드 취소
actions.cancel();

// 특정 파일 취소
actions.cancel('file-id');
매개변수타입설명
fileIdstring (선택사항)취소할 특정 파일 ID

remove(fileId)

목록에서 파일 제거.

actions.remove('file-id');
매개변수타입설명
fileIdstring제거할 파일 ID

reset()

모든 파일 제거 및 상태 초기화.

actions.reset();

retry(fileIds?)

실패한 업로드 재시도.

// 모든 실패한 업로드 재시도
actions.retry();

// 특정 파일 재시도
actions.retry(['file-id-1']);
매개변수타입설명
fileIdsstring[] (선택사항)재시도할 특정 파일 ID

addFiles(files)

프로그래밍 방식으로 파일 추가.

// 클립보드에서
document.addEventListener('paste', (e) => {
const files = e.clipboardData?.files;
if (files) {
actions.addFiles(files);
}
});

// 다른 소스에서
actions.addFiles([file1, file2]);
매개변수타입설명
filesFile[] | FileList추가할 파일

updateFileMeta(fileId, meta)

파일 메타데이터 업데이트.

actions.updateFileMeta('file-id', {
description: '내 사진',
tags: ['휴가', '2024'],
});
매개변수타입설명
fileIdstring업데이트할 파일 ID
metaRecord<string, unknown>병합할 메타데이터

getDropProps

드롭 영역 요소에 스프레드할 props를 반환합니다.

const { getDropProps, getInputProps } = useDropup();

<div {...getDropProps()}>
<input {...getInputProps()} />
파일을 여기에 드롭하세요
</div>

커스텀 Props와 함께

<div
{...getDropProps({
className: 'my-dropzone',
onClick: (e) => {
// 커스텀 클릭 핸들러
console.log('클릭됨!');
},
})}
>
<input {...getInputProps()} />
</div>

반환된 Props

속성타입설명
onDragEnterfunction드래그 진입 핸들러
onDragOverfunction드래그 오버 핸들러
onDragLeavefunction드래그 이탈 핸들러
onDropfunction드롭 핸들러
onClickfunction클릭 핸들러 (대화상자 열기)
rolestring접근성 역할
tabIndexnumber포커스용 탭 인덱스

getInputProps

숨겨진 파일 input에 스프레드할 props를 반환합니다.

const { getInputProps } = useDropup();

<input {...getInputProps()} />

커스텀 Props와 함께

<input
{...getInputProps({
id: 'file-input',
name: 'files',
})}
/>

반환된 Props

속성타입설명
type'file'Input 타입
acceptstring허용된 파일 유형
multipleboolean여러 파일 허용
onChangefunction변경 핸들러
styleobject숨김 스타일

openFileDialog

프로그래밍 방식으로 파일 선택기를 여는 함수입니다.

const { openFileDialog } = useDropup();

<button onClick={openFileDialog}>
파일 찾기
</button>

사용 예제

완전한 파일 목록

function FileList() {
const { files, actions, state } = useDropup({
upload: { url: '/api/upload' },
});

return (
<div>
<h3>파일 ({files.length})</h3>

{files.map(file => (
<div key={file.id}>
{file.preview && (
<img src={file.preview} alt="" width={50} />
)}
<span>{file.name}</span>
<span>{(file.size / 1024).toFixed(1)} KB</span>
<span>{file.status}</span>

{file.status === 'uploading' && (
<progress value={file.progress} max={100} />
)}

{file.status === 'error' && (
<>
<span style={{ color: 'red' }}>{file.error?.message}</span>
<button onClick={() => actions.retry([file.id])}>재시도</button>
</>
)}

<button onClick={() => actions.remove(file.id)}>제거</button>
</div>
))}

{state.isUploading && (
<p>업로드 중... {state.progress}%</p>
)}

<button
onClick={() => actions.upload()}
disabled={state.isUploading || files.length === 0}
>
모두 업로드
</button>

<button onClick={() => actions.reset()}>
모두 지우기
</button>
</div>
);
}

드래그 상태 스타일링

function StyledDropzone() {
const { state, getDropProps, getInputProps } = useDropup({
accept: 'image/*',
});

const getStyle = () => {
if (state.isDragAccept) return { borderColor: 'green', backgroundColor: '#e8f5e9' };
if (state.isDragReject) return { borderColor: 'red', backgroundColor: '#ffebee' };
if (state.isDragging) return { borderColor: 'blue', backgroundColor: '#e3f2fd' };
return { borderColor: 'gray', backgroundColor: 'white' };
};

return (
<div
{...getDropProps()}
style={{
border: '2px dashed',
borderRadius: 8,
padding: 40,
textAlign: 'center',
transition: 'all 0.2s',
...getStyle(),
}}
>
<input {...getInputProps()} />
{state.isDragReject ? (
<p>이미지만 허용됩니다!</p>
) : (
<p>이미지를 여기에 드롭하세요</p>
)}
</div>
);
}