I have a file selector component that is responsible for handling uploading and downloading files. in the component there is function that is responsible for removiong file from input. but based on the type of value that is passed to the component it does not work properly.here is the code:
import { useRef } from "react";
import { FileSelectorProps } from "./file-selector.interface";
import classNames from "classnames";
import { Close, Download, Upload } from "@mui/icons-material";
import { consoleLog } from "@/utils/helper.util";
import { NavLink } from "react-router-dom";
import { URL_STORAGE } from "@/infrastructure/slice/api.slice";
const FileSelector: React.FC<FileSelectorProps> = ({
onChangeFile,
className,
// label,
id,
formClassName,
// requiredInput,
multiple,
fileType,
...props
}) => {
const fileId = id || props.name || `file_${new Date().getTime()}`;
const inputRef = useRef<any>(null);
const handleSelectFile = (e: any) => {
const files = e.target.files;
consoleLog(files)
if (onChangeFile) onChangeFile(files);
};
const clearInput = () => {
if (inputRef.current) {
inputRef.current.value = '';
}
}
const handleRemove = () => {
clearInput();
if (onChangeFile) onChangeFile(null);
};
return (
<>
<div className={classNames("mt-[1.2rem]", formClassName)}>
{/* {label && <Label htmlFor={fileId} required={requiredInput}>{label}</Label>} */}
{/* <div className={classNames("w-full flex items-center leading-none text-sm border border-gray-300 focus:border-cyan-400 outline-0 py-[9px] pr-4 pl-2 rounded-md", className)}> */}
<div className={classNames("w-full flex items-center leading-none text-sm border-b border-gray-300 focus:border-cyan-400 outline-0 pr-4 pl-2", className)}>
<label
htmlFor={fileId}
className="w-full block"
>
<span className={classNames("block w-full text-xs", {
"text-gray-400": !props.value
})}>
{props.value ? `1 فایل انتخاب شده` : 'بارگذاری فایل مرتبط'}
</span>
<input
multiple={multiple}
ref={inputRef}
id={fileId}
type="file"
className='hidden'
onChange={handleSelectFile}
accept={fileType ? `.${fileType}` : '*/*'}
/>
</label>
{props.value && (
<div
className="cursor-pointer h-full text-gray-600 ml-1 z-2"
onClick={handleRemove}
>
<Close className="w-4 h-4" />
</div>
)}
<label htmlFor={fileId}>
{typeof (props.value) === "string" && props.value ?
<NavLink to={`${URL_STORAGE}${props.value}`} target="_blank" >
{typeof (props.value) === "string" && props.value ? <Download color="action" /> : <Upload color="action" />}
</NavLink> : (
<Upload color="action" />
)}
</label>
</div>
</div>
</>
)
}
export default FileSelector;
if props.value would be an object the handleRemove function works but if props.value would be a string the function does not work properly. how can i fix this problem?