Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: clear input value on clearFiles from imperative handle #3090

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion src/components/forms/FileInput/FileInput.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,10 @@ export const WithRefAndCustomHandlers = {
const [files, setFiles] = useState<FileList | null>(null)
const fileInputRef = useRef<FileInputRef>(null)

const handleClearFiles = (): void => fileInputRef.current?.clearFiles()
const handleClearFiles = (): void => {
fileInputRef.current?.clearFiles()
setFiles(null)
}

const handleChange = (e: React.ChangeEvent<HTMLInputElement>): void => {
argTypes.onChange(e)
Expand Down
7 changes: 4 additions & 3 deletions src/components/forms/FileInput/FileInput.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -408,9 +408,10 @@ describe('FileInput component', () => {
'display-none'
)

// Notice how input.files still exist because we can't programmatically set the value
expect(fileInputRef.current?.input?.files).toHaveLength(1)
// But the files state of the React "input" is cleared out
// Inputs files should be cleared out and reset
expect(fileInputRef.current?.input?.files).toHaveLength(0)
expect(fileInputRef.current?.input?.value).toEqual('')
// Files state of the React "input" is cleared out
expect(fileInputRef.current?.files).toHaveLength(0)
})
})
Expand Down
7 changes: 6 additions & 1 deletion src/components/forms/FileInput/FileInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,12 @@ export const FileInputForwardRef: React.ForwardRefRenderFunction<
ref,
() => ({
input: internalRef.current,
clearFiles: (): void => setFiles([]),
clearFiles: (): void => {
setFiles([])
if (internalRef.current) {
internalRef.current.value = ''
}
},
files,
}),
[files]
Expand Down
Loading