Skip to content

Commit 83ee128

Browse files
Allow to reset FileInputField internal state by calling resetState function on its ref (#630)
1 parent 4a11a95 commit 83ee128

File tree

2 files changed

+49
-7
lines changed

2 files changed

+49
-7
lines changed

src/components/FileInputField/FileInputField.jsx

+17-7
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

+32
Original file line numberDiff line numberDiff line change
@@ -236,6 +236,38 @@ 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+
245+
```docoff-react-preview
246+
const fileInputRef = React.useRef();
247+
248+
return (
249+
<>
250+
<FileInputField
251+
label="Attachment"
252+
onFilesChanged={() => {}}
253+
ref={fileInputRef}
254+
/>
255+
<Button
256+
label="Reset file input state"
257+
onClick={() => {
258+
if (!fileInputRef.current) {
259+
return;
260+
}
261+
fileInputRef.current.resetState();
262+
}}
263+
/>
264+
</>
265+
);
266+
```
267+
268+
You can also reset the input state by clicking the button with the `reset` type
269+
inside the form.
270+
239271
## Forwarding HTML Attributes
240272

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

0 commit comments

Comments
 (0)