91 lines
2.9 KiB
TypeScript
91 lines
2.9 KiB
TypeScript
import { type FC, useCallback, useEffect, useState } from 'react'
|
|
import { useTranslation } from 'react-i18next'
|
|
import { useDropzone } from 'react-dropzone'
|
|
import { CloseCircle } from 'iconsax-react'
|
|
|
|
|
|
type Props = {
|
|
label: string,
|
|
isMultiple?: boolean,
|
|
onChange?: (file: File[]) => void;
|
|
isReset?: boolean;
|
|
}
|
|
|
|
const UploadBox: FC<Props> = (props: Props) => {
|
|
|
|
const { t } = useTranslation('global')
|
|
const [files, setFiles] = useState<File[]>([])
|
|
|
|
const onDrop = useCallback((acceptedFiles: File[]) => {
|
|
if (props.isMultiple) {
|
|
const array = [...files]
|
|
array.push(acceptedFiles[0])
|
|
setFiles(array)
|
|
if (props.onChange) {
|
|
props.onChange(array);
|
|
}
|
|
} else {
|
|
setFiles([acceptedFiles[0]])
|
|
if (props.onChange) {
|
|
props.onChange([acceptedFiles[0]])
|
|
}
|
|
}
|
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
}, [files])
|
|
const { getRootProps, getInputProps } = useDropzone({ onDrop })
|
|
|
|
const handleRemove = (index: number) => {
|
|
const array = [...files]
|
|
array.splice(index, 1)
|
|
setFiles(array)
|
|
if (props.onChange) {
|
|
props.onChange(array)
|
|
}
|
|
}
|
|
|
|
useEffect(() => {
|
|
|
|
if (props.isReset) {
|
|
setFiles([])
|
|
}
|
|
|
|
}, [props.isReset])
|
|
|
|
|
|
|
|
return (
|
|
<div>
|
|
<div className='text-sm'>{props.label}</div>
|
|
<div className='w-full h-10 mt-1 border border-border rounded-xl items-center px-2 flex gap-2.5'>
|
|
<button {...getRootProps()} className=' w-fit h-7 rounded-lg text-xs px-6 bg-secondary'>
|
|
<input {...getInputProps()} />
|
|
|
|
{t('select_file')}
|
|
</button>
|
|
|
|
<div className='lg:flex gap-2 hidden'>
|
|
{
|
|
files?.map((item, index) => (
|
|
<div key={index} className='flex bg-gray-200 py-1.5 px-2 rounded-lg items-center gap-1'>
|
|
<CloseCircle onClick={() => handleRemove(index)} size={16} color='red' />
|
|
<div className='text-xs'>{item.name}</div>
|
|
</div>
|
|
))
|
|
}
|
|
</div>
|
|
</div>
|
|
<div className='lg:hidden gap-2 flex flex-wrap mt-4'>
|
|
{
|
|
files?.map((item, index) => (
|
|
<div key={index} className='flex bg-gray-200 py-1.5 px-2 rounded-lg items-center gap-1'>
|
|
<CloseCircle onClick={() => handleRemove(index)} size={16} color='red' />
|
|
<div className='text-xs'>{item.name}</div>
|
|
</div>
|
|
))
|
|
}
|
|
</div>
|
|
</div>
|
|
)
|
|
}
|
|
|
|
export default UploadBox |