From 05bc61ab1be44a247f9b3f217d2879c4878efdc4 Mon Sep 17 00:00:00 2001 From: Florian Scholdei Date: Thu, 4 May 2023 08:22:02 +0200 Subject: [PATCH] Use forwardRef in FileInput Committed-by: Rene Pfeuffer --- gradle/changelog/fileinput_forwardref.yaml | 2 + scm-ui/ui-components/src/forms/FileInput.tsx | 117 +++++++++---------- 2 files changed, 55 insertions(+), 64 deletions(-) create mode 100644 gradle/changelog/fileinput_forwardref.yaml diff --git a/gradle/changelog/fileinput_forwardref.yaml b/gradle/changelog/fileinput_forwardref.yaml new file mode 100644 index 0000000000..db0d4813da --- /dev/null +++ b/gradle/changelog/fileinput_forwardref.yaml @@ -0,0 +1,2 @@ +- type: fixed + description: Allow passing a ref through FileInput to one of its children diff --git a/scm-ui/ui-components/src/forms/FileInput.tsx b/scm-ui/ui-components/src/forms/FileInput.tsx index 057823327b..8aa810f7bf 100644 --- a/scm-ui/ui-components/src/forms/FileInput.tsx +++ b/scm-ui/ui-components/src/forms/FileInput.tsx @@ -21,7 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -import React, { ChangeEvent, FC, FocusEvent, useState } from "react"; +import React, { ChangeEvent, FocusEvent, useState } from "react"; import { useTranslation } from "react-i18next"; import classNames from "classnames"; import { createAttributesForTesting } from "../devBuild"; @@ -39,77 +39,66 @@ type Props = { testId?: string; onChange?: (event: ChangeEvent) => void; onBlur?: (event: FocusEvent) => void; - ref?: React.Ref; }; -const FileInput: FC = ({ - name, - filenamePlaceholder, - testId, - helpText, - placeholder, - disabled, - label, - className, - ref, - onBlur, - onChange, -}) => { - const [t] = useTranslation("commons"); - const [file, setFile] = useState(null); +const FileInput = React.forwardRef( + ({ name, filenamePlaceholder, testId, helpText, placeholder, disabled, label, className, onBlur, onChange }, ref) => { + const [t] = useTranslation("commons"); + const [file, setFile] = useState(null); - const handleChange = (event: ChangeEvent) => { - const uploadedFile = event?.target?.files![0]; - // @ts-ignore the uploaded file doesn't match our types - setFile(uploadedFile); + const handleChange = (event: ChangeEvent) => { + const uploadedFile = event?.target?.files![0]; + // @ts-ignore the uploaded file doesn't match our types + setFile(uploadedFile); - if (onChange && event.target.files) { - onChange(event); - } - }; + if (onChange && event.target.files) { + onChange(event); + } + }; - const handleBlur = (event: FocusEvent) => { - if (onBlur && event.target.files) { - onBlur(event); - } - }; + const handleBlur = (event: FocusEvent) => { + if (onBlur && event.target.files) { + onBlur(event); + } + }; - const id = createA11yId("file-input"); + const id = createA11yId("file-input"); - return ( -
- -
-
- ); -}; + ); + } +); export default FileInput;