You are an expert software engineer specialised in Next.js 14 with TypeScript and TailwindCSS. When programming your solution effectiveness, efficiency and readability rank at the top of your principles. You employ industry best practices. I need you to extend my ShadCN Textarea by having three modes: free, fixed and adaptive. Free allows users to resize the Textarea component. Fixed fixes the height of the Textarea to the specified row. Adaptive makes the row the minimum height but its height depending on the height of the input content.
You are an expert software engineer specialised in Next.js… · The Chat Archive
To extend your ShadCN Textarea component with three modes—free, fixed, and adaptive—we'll introduce a mode prop that controls the behavior and styling of the textarea. Here's how each mode will function:
Free Mode:
Behavior: Users can freely resize the textarea.
Styling: Allows resizing by applying the appropriate Tailwind CSS classes.
Fixed Mode:
Behavior: The textarea has a fixed height based on the specified number of rows.
Styling: Disables resizing and sets a fixed number of rows.
Adaptive Mode:
Behavior: The textarea starts with a minimum height based on the specified number of rows and automatically adjusts its height based on the content.
Styling: Disables manual resizing and employs JavaScript to adjust the height dynamically.
Below is the updated Textarea component implementing these features:
components/ui/textarea.tsx
tsx
import * as React from "react";
import { cn } from "@/lib/utils";
// Define the available modes as a TypeScript union type
type TextareaMode = "free" | "fixed" | "adaptive";
export interface TextareaProps
extends React.TextareaHTMLAttributes<HTMLTextAreaElement> {
/**
* Controls the behavior and styling of the textarea.
* - "free": Users can resize the textarea.
* - "fixed": The textarea has a fixed height based on the `rows` prop.
* - "adaptive": The textarea adjusts its height based on content.
*/
mode?: TextareaMode;
/**
* Specifies the number of visible text lines for the textarea.
* Used in "fixed" and "adaptive" modes.
* @default 3
*/
rows?: number;
}
const Textarea = React.forwardRef<HTMLTextAreaElement, TextareaProps>(
(
{
className,
mode = "free",
rows = 3,
style,
onInput,
...props
},
ref
) => {
// Create a local ref to handle adaptive behavior
const localRef = React.useRef<HTMLTextAreaElement>(null);
// Combine forwarded ref and local ref
React.useImperativeHandle(ref, () => localRef.current as HTMLTextAreaElement);
/**
* Adjusts the height of the textarea to fit content.
* Only applicable in "adaptive" mode.
*/
const adjustHeight = React.useCallback(() => {
const textarea = localRef.current;
if (textarea) {
textarea.style.height = "auto"; // Reset height to calculate new height
textarea.style.height = `${textarea.scrollHeight}px`;
}
}, []);
/**
* Effect to adjust height on component mount and when content changes.
*/
React.useEffect(() => {
if (mode === "adaptive") {
adjustHeight();
}
}, [mode, adjustHeight, props.value]);
/**
* Handler for the input event.
* Calls the user's onInput prop and adjusts height if in "adaptive" mode.
*/
const handleInput = (event: React.FormEvent<HTMLTextAreaElement>) => {
if (mode === "adaptive") {
adjustHeight();
}
if (onInput) {
onInput(event);
}
};
// Determine resize behavior based on mode
const resizeClass = React.useMemo(() => {
switch (mode) {
case "free":
return "resize";
case "fixed":
case "adaptive":
return "resize-none";
default:
return "";
}
}, [mode]);
// Determine rows attribute
const rowsAttribute = mode === "fixed" || mode === "adaptive" ? rows : undefined;
// Combine all Tailwind CSS classes
const combinedClasses = cn(
"flex w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",
resizeClass,
{
// Set a minimum height for adaptive mode
"min-h-[60px]": mode === "adaptive",
},
className
);
return (
<textarea
className={combinedClasses}
ref={localRef}
rows={rowsAttribute}
style={mode === "adaptive" ? { ...style, overflow: "hidden" } : style}
{...props}
onInput={handleInput}
/>
);
}
);
Textarea.displayName = "Textarea";
export { Textarea };
Explanation of Changes
Mode Prop:
Added a mode prop to the TextareaProps interface, allowing users to select between "free", "fixed", and "adaptive" modes.
Provided TypeScript typing for the mode prop to ensure type safety.
Rows Prop:
Added a rows prop to specify the number of visible text lines. This is particularly useful for "fixed" and "adaptive" modes.
Set a default value of 3 if rows is not provided.
Resize Behavior:
Utilized the resizeClass variable to conditionally apply Tailwind CSS classes based on the selected mode:
"free": Applies resize, allowing users to resize the textarea.
"fixed" and "adaptive": Applies resize-none, disabling manual resizing.
Adaptive Mode Functionality:
Introduced a localRef using useRef to directly manipulate the DOM for auto-resizing.
Used useImperativeHandle to ensure the forwarded ref points to localRef, maintaining ref forwarding best practices.
Created an adjustHeight function that resets the textarea's height to auto and then sets it to its scrollHeight, ensuring the textarea grows to fit its content.
Employed useEffect to call adjustHeight whenever the component mounts or when the value prop changes, ensuring the height stays in sync with the content.
Overrode the onInput event to include the adjustHeight functionality while preserving any user-provided onInput handlers.
Styling Adjustments:
For "adaptive" mode, added min-h-[60px] to ensure a reasonable minimum height.
Set the overflow style to hidden in "adaptive" mode to prevent scrollbars from appearing as the textarea grows.
:
Usage Examples
Here's how you can utilize the extended Textarea component in different modes:
tsx
import { Textarea } from "@/components/ui/textarea";
function ExampleComponent() {
return (
<div className="space-y-4">
{/* Free Mode: Users can resize the textarea */}
<Textarea
mode="free"
placeholder="This textarea can be resized freely."
/>
{/* Fixed Mode: Fixed height based on 5 rows */}
<Textarea
mode="fixed"
rows={5}
placeholder="This textarea has a fixed height."
/>
{/* Adaptive Mode: Height adjusts based on content */}
<Textarea
mode="adaptive"
rows={3}
placeholder="This textarea adapts its height based on content."
/>
</div>
);
}
export default ExampleComponent;
Additional Considerations
Controlled vs. Uncontrolled:
The adaptive mode works seamlessly with both controlled and uncontrolled components. Ensure that when using controlled components (where the value prop is managed by state), the height adjusts correctly by passing the updated value prop.
Styling Customizations:
You can further customize the minimum height or other styles by modifying the Tailwind classes or extending the component with additional props.
Performance:
The adjustHeight function is memoized using useCallback to prevent unnecessary re-creations, ensuring efficient performance.
By implementing these changes, your Textarea component is now more versatile, catering to different user interface requirements while maintaining high standards of code quality and performance.