From c8fd29101316aa81d032ccba6f561bbb124e6bab Mon Sep 17 00:00:00 2001 From: Bree Hall <40739624+breehall@users.noreply.github.com> Date: Tue, 10 May 2022 15:37:07 -0400 Subject: [PATCH] [EuiForm] Enable `ref` Prop for EuiForm (#5866) * Enabled ref prop for EuiForm * Changelog * Update src/components/form/form.tsx Co-authored-by: Greg Thompson Co-authored-by: Greg Thompson --- src/components/form/form.tsx | 125 +++++++++++++++++++---------------- upcoming_changelogs/5866.md | 1 + 2 files changed, 69 insertions(+), 57 deletions(-) create mode 100644 upcoming_changelogs/5866.md diff --git a/src/components/form/form.tsx b/src/components/form/form.tsx index cb49efc755c..3944cf4dd54 100644 --- a/src/components/form/form.tsx +++ b/src/components/form/form.tsx @@ -7,11 +7,11 @@ */ import React, { - FunctionComponent, ReactNode, HTMLAttributes, FormHTMLAttributes, useCallback, + forwardRef, } from 'react'; import classNames from 'classnames'; import { EuiCallOut } from '../call_out'; @@ -35,67 +35,78 @@ export type EuiFormProps = CommonProps & invalidCallout?: 'above' | 'none'; }; -export const EuiForm: FunctionComponent = ({ - children, - className, - isInvalid, - error, - component = 'div', - invalidCallout = 'above', - ...rest -}) => { - const handleFocus = useCallback((node) => { - node?.focus(); - }, []); +export const EuiForm = forwardRef( + ( + { + children, + className, + isInvalid, + error, + component = 'div', + invalidCallout = 'above', + ...rest + }, + ref + ) => { + const handleFocus = useCallback((node) => { + node?.focus(); + }, []); - const classes = classNames('euiForm', className); + const classes = classNames('euiForm', className); - let optionalErrors: JSX.Element | null = null; + let optionalErrors: JSX.Element | null = null; - if (error) { - const errorTexts = Array.isArray(error) ? error : [error]; - optionalErrors = ( -
    - {errorTexts.map((error, index) => ( -
  • - {error} -
  • - ))} -
- ); - } + if (error) { + const errorTexts = Array.isArray(error) ? error : [error]; + optionalErrors = ( +
    + {errorTexts.map((error, index) => ( +
  • + {error} +
  • + ))} +
+ ); + } + + let optionalErrorAlert; - let optionalErrorAlert; + if (isInvalid && invalidCallout === 'above') { + optionalErrorAlert = ( + + {(addressFormErrors: string) => ( + + {optionalErrors} + + )} + + ); + } - if (isInvalid && invalidCallout === 'above') { - optionalErrorAlert = ( - or
, but TypeScript wants to support both + ref={ref} + className={classes} + {...(rest as HTMLAttributes)} > - {(addressFormErrors: string) => ( - - {optionalErrors} - - )} - + {optionalErrorAlert} + {children} + ); } - - const Element = component; - - return ( - )}> - {optionalErrorAlert} - {children} - - ); -}; +); +EuiForm.displayName = 'EuiForm'; diff --git a/upcoming_changelogs/5866.md b/upcoming_changelogs/5866.md new file mode 100644 index 00000000000..ed8bd242b2c --- /dev/null +++ b/upcoming_changelogs/5866.md @@ -0,0 +1 @@ +- Updated `EuiForm` to use `forwardRef`