Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[DS-276] Resize TextArea when value changes with a debounce #851

Merged
merged 1 commit into from
Sep 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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;
}
Loading