@drivy/cobalt
Version:
Opinionated design system for Drivy's projects.
51 lines (48 loc) • 2.1 kB
JavaScript
import React, { forwardRef, useRef, useState, useEffect } from 'react';
import cx from 'classnames';
import { withFieldLabelAndHint } from './field.js';
const TextArea = forwardRef((props, ref) => {
const { autosize, className, inputClassName, status, maxLength, onChange, ...nativeProps } = props;
const internalRef = useRef(null);
const [length, setLength] = useState(0);
const [height, setHeight] = useState(0);
const hasAutosize = autosize || (maxLength && maxLength > 0);
useEffect(() => {
if (ref && "current" in ref) {
ref.current = internalRef.current;
}
}, [ref]);
const handleAutosize = (el) => {
if (!el)
return;
if (hasAutosize) {
setLength(el.value.length);
setHeight(el.scrollHeight + 2);
}
};
useEffect(() => {
handleAutosize(internalRef.current);
}, [autosize, maxLength]);
const handleChange = (event) => {
handleAutosize(event.target);
onChange && onChange(event);
};
return (React.createElement("div", { className: cx("cobalt-TextAreaField", className, {
"cobalt-TextAreaField--withLimit": maxLength && maxLength > 0,
"cobalt-TextAreaField--success": status === "success",
"cobalt-TextAreaField--error": status === "error",
}) },
React.createElement("textarea", { ...nativeProps, maxLength: maxLength, style: hasAutosize
? {
height: height + "px",
}
: {}, onChange: handleChange, className: cx("cobalt-TextAreaField__Input", inputClassName), ref: internalRef }),
length > 0 && maxLength && maxLength > 0 && (React.createElement("div", { className: "cobalt-TextAreaField__RemainingChars" },
maxLength - length,
" remaining characters"))));
});
TextArea.displayName = "TextArea";
const wrappedComponent = withFieldLabelAndHint(TextArea);
wrappedComponent.displayName = "TextArea";
export { wrappedComponent as TextArea };
//# sourceMappingURL=TextArea.js.map