Skip to content

Commit

Permalink
feat(form): updated TextArea to use the new useResizeObserver API
Browse files Browse the repository at this point in the history
  • Loading branch information
mlaursen committed Sep 1, 2020
1 parent 052b3f2 commit 2c2dd27
Showing 1 changed file with 10 additions and 7 deletions.
17 changes: 10 additions & 7 deletions packages/form/src/text-field/TextArea.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import React, {
TextareaHTMLAttributes,
useCallback,
useState,
useRef,
} from "react";
import cn from "classnames";
import { bem, useEnsuredRef, useResizeObserver } from "@react-md/utils";
Expand Down Expand Up @@ -168,9 +169,10 @@ const TextArea = forwardRef<HTMLTextAreaElement, TextAreaProps>(
setHeight(undefined);
}

const [mask, setMask] = useState<HTMLTextAreaElement | null>(null);
const maskRef = useRef<HTMLTextAreaElement | null>(null);
const [scrollable, setScrollable] = useState(false);
const updateHeight = (): void => {
const updateHeight = useCallback(() => {
const mask = maskRef.current;
if (!mask) {
return;
}
Expand All @@ -195,19 +197,20 @@ const TextArea = forwardRef<HTMLTextAreaElement, TextAreaProps>(
if (height !== nextHeight) {
setHeight(nextHeight);
}
};
}, [height, maxRows, scrollable]);

// the window can be resized while there is text inside the textarea so need to
// recalculate the height when the width changes as well.
useResizeObserver({
const [, maskRefHandler] = useResizeObserver(updateHeight, {
ref: maskRef,
disableHeight: true,
target: mask,
onResize: updateHeight,
});

const [valued, onChange] = useValuedState<HTMLTextAreaElement>({
value,
defaultValue,
onChange: (event) => {
const mask = maskRef.current;
if (propOnChange) {
propOnChange(event);
}
Expand Down Expand Up @@ -286,7 +289,7 @@ const TextArea = forwardRef<HTMLTextAreaElement, TextAreaProps>(
aria-hidden
defaultValue={value || defaultValue}
id={`${id}-mask`}
ref={setMask}
ref={maskRefHandler}
readOnly
rows={rows}
tabIndex={-1}
Expand Down

0 comments on commit 2c2dd27

Please sign in to comment.