ConceptPortal-public/rsconcept/frontend/src/components/Common/FileInput.tsx

57 lines
1.4 KiB
TypeScript
Raw Normal View History

2023-07-15 17:46:19 +03:00
import { useRef, useState } from 'react';
2023-07-25 20:27:29 +03:00
2023-07-15 17:46:19 +03:00
import { UploadIcon } from '../Icons';
import Button from './Button';
import Label from './Label';
interface FileInputProps {
2023-07-27 22:04:25 +03:00
id?: string
2023-07-15 17:46:19 +03:00
required?: boolean
label: string
acceptType?: string
widthClass?: string
onChange?: (event: React.ChangeEvent<HTMLInputElement>) => void
}
2023-07-25 20:27:29 +03:00
function FileInput({ id, required, label, acceptType, widthClass = 'w-full', onChange }: FileInputProps) {
2023-07-15 17:46:19 +03:00
const inputRef = useRef<HTMLInputElement | null>(null);
const [labelText, setLabelText] = useState('Файл не выбран');
2023-07-25 20:27:29 +03:00
2023-07-15 17:46:19 +03:00
const handleUploadClick = () => {
inputRef.current?.click();
};
const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
2023-07-25 20:27:29 +03:00
if (event.target.files && event.target.files.length > 0) {
2023-07-15 17:46:19 +03:00
setLabelText(event.target.files[0].name)
} else {
setLabelText('Файл не выбран')
}
if (onChange) {
onChange(event);
}
};
2023-07-25 20:27:29 +03:00
2023-07-15 17:46:19 +03:00
return (
2023-07-27 22:04:25 +03:00
<div className={'flex flex-col gap-2 py-2 [&:not(:first-child)]:mt-3 items-start ' + widthClass}>
2023-07-15 17:46:19 +03:00
<input id={id} type='file'
ref={inputRef}
required={required}
style={{ display: 'none' }}
accept={acceptType}
onChange={handleFileChange}
/>
2023-07-25 20:27:29 +03:00
<Button
2023-07-15 17:46:19 +03:00
text={label}
icon={<UploadIcon/>}
onClick={handleUploadClick}
/>
2023-07-25 20:27:29 +03:00
<Label
2023-07-15 17:46:19 +03:00
text={labelText}
/>
</div>
);
}
2023-07-25 20:27:29 +03:00
export default FileInput;