import React, { useMemo } from 'react'; import { v4 as uuidv4 } from 'uuid'; import Checkbox from '../checkbox/checkbox'; import HStack from '../hstack/hstack'; import Stack from '../stack/stack'; interface IFormGroup { /** Input label message. */ labelText?: React.ReactNode /** Input label tooltip message. */ labelTitle?: string /** Input hint message. */ hintText?: React.ReactNode /** Input errors. */ errors?: string[] /** Elements to display within the FormGroup. */ children: React.ReactNode } /** Input container with label. Renders the child. */ const FormGroup: React.FC = (props) => { const { children, errors = [], labelText, labelTitle, hintText } = props; const formFieldId: string = useMemo(() => `field-${uuidv4()}`, []); const inputChildren = React.Children.toArray(children); const hasError = errors?.length > 0; let firstChild; if (React.isValidElement(inputChildren[0])) { firstChild = React.cloneElement( inputChildren[0], { id: formFieldId }, ); } const isCheckboxFormGroup = firstChild?.type === Checkbox; if (isCheckboxFormGroup) { return ( {firstChild} {labelText && ( )} {hasError && (

{errors.join(', ')}

)} {hintText && (

{hintText}

)}
); } return (
{labelText && ( )}
{firstChild} {inputChildren.filter((_, i) => i !== 0)} {hasError && (

{errors.join(', ')}

)} {hintText && (

{hintText}

)}
); }; export default FormGroup;