반환 값 레퍼런스
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 속성
| 속성 | 타입 | 설명 |
|---|---|---|
id | string | 고유 식별자 |
file | File | 원본 브라우저 File 객체 |
name | string | 파일 이름 |
size | number | 바이트 단위 크기 |
type | string | MIME 타입 |
status | FileStatus | 현재 상태 |
progress | number | 업로드 진행률 (0-100) |
preview | string | undefined | 이미지용 미리보기 URL |
uploadedUrl | string | undefined | 업로드 성공 후 URL |
response | unknown | 서버 응답 데이터 |
error | DropupError | undefined | 업로드 실패 시 오류 |
meta | Record<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 속성
| 속성 | 타입 | 설명 |
|---|---|---|
isDragging | boolean | 파일이 드롭 영역 위에서 드래그 중 |
isDragAccept | boolean | 드래그된 파일이 유효성 검사 통과 |
isDragReject | boolean | 드래그된 파일이 유효성 검사 실패 |
isUploading | boolean | 현재 업로드 중인 파일 있음 |
progress | number | 모든 파일의 평균 진행률 (0-100) |
status | DropupStatus | 전체 업로드 상태 |
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']);
| 매개변수 | 타입 | 설명 |
|---|---|---|
fileIds | string[] (선택사항) | 업로드할 특정 파일 ID |
cancel(fileId?)
진행 중인 업로드 취소.
// 모든 업로드 취소
actions.cancel();
// 특정 파일 취소
actions.cancel('file-id');
| 매개변수 | 타입 | 설명 |
|---|---|---|
fileId | string (선택사항) | 취소할 특정 파일 ID |
remove(fileId)
목록에서 파일 제거.
actions.remove('file-id');
| 매개변수 | 타입 | 설명 |
|---|---|---|
fileId | string | 제거할 파일 ID |
reset()
모든 파일 제거 및 상태 초기화.
actions.reset();
retry(fileIds?)
실패한 업로드 재시도.
// 모든 실패한 업로드 재시도
actions.retry();
// 특정 파일 재시도
actions.retry(['file-id-1']);
| 매개변수 | 타입 | 설명 |
|---|---|---|
fileIds | string[] (선택사항) | 재시도할 특정 파일 ID |
addFiles(files)
프로그래밍 방식으로 파일 추가.
// 클립보드에서
document.addEventListener('paste', (e) => {
const files = e.clipboardData?.files;
if (files) {
actions.addFiles(files);
}
});
// 다른 소스에서
actions.addFiles([file1, file2]);
| 매개변수 | 타입 | 설명 |
|---|---|---|
files | File[] | FileList | 추가할 파일 |
updateFileMeta(fileId, meta)
파일 메타데이터 업데이트.
actions.updateFileMeta('file-id', {
description: '내 사진',
tags: ['휴가', '2024'],
});
| 매개변수 | 타입 | 설명 |
|---|---|---|
fileId | string | 업데이트할 파일 ID |
meta | Record<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
| 속성 | 타입 | 설명 |
|---|---|---|
onDragEnter | function | 드래그 진입 핸들러 |
onDragOver | function | 드래그 오버 핸들러 |
onDragLeave | function | 드래그 이탈 핸들러 |
onDrop | function | 드롭 핸들러 |
onClick | function | 클릭 핸들러 (대화상자 열기) |
role | string | 접근성 역할 |
tabIndex | number | 포커스용 탭 인덱스 |
getInputProps
숨겨진 파일 input에 스프레드할 props를 반환합니다.
const { getInputProps } = useDropup();
<input {...getInputProps()} />
커스텀 Props와 함께
<input
{...getInputProps({
id: 'file-input',
name: 'files',
})}
/>
반환된 Props
| 속성 | 타입 | 설명 |
|---|---|---|
type | 'file' | Input 타입 |
accept | string | 허용된 파일 유형 |
multiple | boolean | 여러 파일 허용 |
onChange | function | 변경 핸들러 |
style | object | 숨김 스타일 |
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>
);
}