Skip to content

Commit 3a48e75

Browse files
Allow to reset FileInputField internal state by calling resetState function on its ref (#630)
1 parent 40eaa8d commit 3a48e75

File tree

2 files changed

+48
-7
lines changed

2 files changed

+48
-7
lines changed

src/components/FileInputField/FileInputField.jsx

Lines changed: 17 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -37,20 +37,30 @@ export const FileInputField = React.forwardRef((props, ref) => {
3737
...restProps
3838
} = props;
3939

40-
const internalInputRef = useRef();
41-
42-
// We need to have a reference to the input element to be able to call its methods,
43-
// but at the same time we want to expose this reference to the parent component for
44-
// case someone wants to call input methods from outside the component.
45-
useImperativeHandle(ref, () => internalInputRef.current);
46-
4740
const formLayoutContext = useContext(FormLayoutContext);
4841
const inputGroupContext = useContext(InputGroupContext);
4942
const translations = useContext(TranslationsContext);
5043

5144
const [selectedFileNames, setSelectedFileNames] = useState([]);
5245
const [isDragging, setIsDragging] = useState(false);
5346

47+
const internalInputRef = useRef();
48+
49+
// We need to have a reference to the input element to be able to call its methods,
50+
// but at the same time we want to expose this reference to the parent component for
51+
// case someone wants to call input methods from outside the component.
52+
useImperativeHandle(
53+
ref,
54+
() => {
55+
const inputEl = internalInputRef?.current ?? {};
56+
inputEl.resetState = () => {
57+
setSelectedFileNames([]);
58+
};
59+
return inputEl;
60+
},
61+
[setSelectedFileNames],
62+
);
63+
5464
const handleFileChange = (files, event) => {
5565
if (files.length === 0) {
5666
setSelectedFileNames([]);

src/components/FileInputField/README.md

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -236,6 +236,37 @@ set the `multiple` prop to `true`.
236236
/>
237237
```
238238

239+
## Resetting Input State
240+
241+
If you need to reset the input state, you can do it by calling the
242+
`resetState` method on the component's ref.
243+
244+
```docoff-react-preview
245+
const fileInputRef = React.useRef();
246+
247+
return (
248+
<>
249+
<FileInputField
250+
label="Attachment"
251+
onFilesChanged={() => {}}
252+
ref={fileInputRef}
253+
/>
254+
<Button
255+
label="Reset file input state"
256+
onClick={() => {
257+
if (!fileInputRef.current) {
258+
return;
259+
}
260+
fileInputRef.current.resetState();
261+
}}
262+
/>
263+
</>
264+
);
265+
```
266+
267+
You can also reset the input state by clicking the button with the `reset` type
268+
inside the form.
269+
239270
## Forwarding HTML Attributes
240271

241272
In addition to the options below in the [component's API](#api) section, you

0 commit comments

Comments
 (0)