Skip to content

Commit

Permalink
[DS-276] Resize TextArea when value changes with a debounce (#851)
Browse files Browse the repository at this point in the history
  • Loading branch information
victortrinh2 committed Sep 18, 2024
1 parent 2afe0d0 commit 8e702ce
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 1 deletion.
5 changes: 5 additions & 0 deletions .changeset/seven-rice-hang.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@igloo-ui/textarea": patch
---

Resize textarea on value change with a 300ms debounce
4 changes: 3 additions & 1 deletion packages/Textarea/src/Textarea.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import useCharLength from "./hooks/useCharLength";
import useTruncateValue from "./hooks/useTruncateValue";

import "./textarea.scss";
import { useDebounce } from "./hooks/useDebounce";

export interface TextareaProps extends React.ComponentPropsWithRef<"textarea"> {
/** True if the textarea should allow new lines with Enter. */
Expand Down Expand Up @@ -58,6 +59,7 @@ const Textarea: React.FunctionComponent<TextareaProps> = React.forwardRef(
const textareaRef = React.useRef<HTMLTextAreaElement | null>(null);
const mergedTextareaRef = mergeRefs(textareaRef, ref);
const [currentValue, setCurrentValue] = React.useState(value ?? "");
const debounceCurrentValue = useDebounce(currentValue, 300);
const textareaMaxLength = maxLength ?? 0;
const charLength = useCharLength(currentValue, textareaMaxLength);
const displayCharIndicator =
Expand Down Expand Up @@ -106,7 +108,7 @@ const Textarea: React.FunctionComponent<TextareaProps> = React.forwardRef(
autosize(textareaRef.current);
autosize.update(textareaRef.current);
}
}, [textareaRef, isAutoResize]);
}, [textareaRef, isAutoResize, debounceCurrentValue]);

React.useEffect(() => {
const newValue = truncateValue(value?.toString() ?? "", maxLength);
Expand Down
17 changes: 17 additions & 0 deletions packages/Textarea/src/hooks/useDebounce.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { useEffect, useState } from "react";

export function useDebounce<T>(value: T, delay: number): T {
const [debouncedValue, setDebouncedValue] = useState<T>(value);

useEffect(() => {
const handler = setTimeout(() => {
setDebouncedValue(value);
}, delay);

return () => {
clearTimeout(handler);
};
}, [value, delay]);

return debouncedValue;
}

0 comments on commit 8e702ce

Please sign in to comment.