import React, {Children, cloneElement, isValidElement} from "react"; import TextareaProps from "./Textarea.types"; import ErrorMessage from "../ErrorMessage"; import FormGroup from "../../layout/FormGroup"; import Hint from "../Hint"; import Label from "../Label"; export const Textarea = ({ name, id, rows, autocomplete, spellcheck, classes, errorMessage, attributes, children, prefix, suffix, describedBy, value, }: TextareaProps) => { if (!id && name) { id = name; } else if (!name && id) { name = id; } let describedByValue = describedBy || ''; let errorMessageComponent; if (errorMessage) { const errorId = id ? `${id}-error` : ''; describedByValue += ` ${errorId}`; errorMessageComponent = {errorMessage}; } const arrayChildren: any = Children.toArray(children); const PrefixSuffixWrapper = ({children}: any) => { if (prefix || suffix) { return ( <>
{ prefix && (
{prefix}
)} {children} { suffix && (
{suffix}
)}
) } else return children; }; return ( <> { Children.map(arrayChildren, (child:any, _index) => { if (isValidElement(child) && (child.type === Label)) { return ( <> { cloneElement(child as React.ReactElement, { htmlFor: id }) } ); } if (isValidElement(child) && (child.type === Hint)) { describedByValue += ` ${id}-hint`; return ( <> { cloneElement(child as React.ReactElement, { id: `${id}-hint` }) } ); } })} {errorMessageComponent}