0
Fork 0
mirror of https://github.com/TryGhost/Ghost.git synced 2025-01-06 22:40:14 -05:00

Fixed file upload not triggering for same file selection

refs https://github.com/TryGhost/Team/issues/3432

File upload component was not firing `onChange` when user attempts to upload the same again, which is a side-effect of `input` field behavior. This change resets the file input on every upload with a new key so that the upload always fires
This commit is contained in:
Rishabh 2023-06-15 20:59:39 +05:30
parent 9ce4c85905
commit 44a07e04e2

View file

@ -1,4 +1,4 @@
import React, {ChangeEvent} from 'react'; import React, {ChangeEvent, useState} from 'react';
export interface FileUploadProps { export interface FileUploadProps {
id: string; id: string;
@ -15,16 +15,19 @@ export interface FileUploadProps {
} }
const FileUpload: React.FC<FileUploadProps> = ({id, onUpload, children, style, ...props}) => { const FileUpload: React.FC<FileUploadProps> = ({id, onUpload, children, style, ...props}) => {
const [fileKey, setFileKey] = useState<number>(Date.now());
const handleFileChange = (event: ChangeEvent<HTMLInputElement>) => { const handleFileChange = (event: ChangeEvent<HTMLInputElement>) => {
const selectedFile = event.target.files?.[0]; const selectedFile = event.target.files?.[0];
if (selectedFile) { if (selectedFile) {
onUpload?.(selectedFile); onUpload?.(selectedFile);
} }
setFileKey(Date.now());
}; };
return ( return (
<label htmlFor={id} style={style} {...props}> <label htmlFor={id} style={style} {...props}>
<input id={id} type="file" hidden onChange={handleFileChange} /> <input key={fileKey} id={id} type="file" hidden onChange={handleFileChange} />
{(typeof children === 'string') ? {(typeof children === 'string') ?
<div className='inline-flex h-[34px] cursor-pointer items-center justify-center rounded px-4 text-sm font-semibold hover:bg-grey-100'> <div className='inline-flex h-[34px] cursor-pointer items-center justify-center rounded px-4 text-sm font-semibold hover:bg-grey-100'>
{children} {children}