react-textarea-autosize
react-textarea-autosize copied to clipboard
Cursor not at the end of input when using autofocus with initial value
Repro: https://stackblitz.com/edit/vitejs-vite-b4qb54?file=src%2FApp.jsx&terminal=dev
Temporary solution: Uncomment FixedTextarea line
import React, {
forwardRef,
useRef,
useImperativeHandle,
useLayoutEffect,
} from "react";
import {
TextareaAutosize,
TextareaAutosizeProps,
} from "react-textarea-autosize";
const Textarea = forwardRef(
(props: TextareaAutosizeProps, ref: React.Ref<HTMLTextAreaElement>) => {
const { autoFocus, ...restProps } = props;
const textareaRef = useRef<HTMLTextAreaElement>(null);
useImperativeHandle(ref, () => textareaRef.current!, []);
useLayoutEffect(() => {
if (autoFocus && textareaRef.current) {
const textarea = textareaRef.current;
textarea.focus();
// Focus to the end
const length = textarea.value.length;
textarea.setSelectionRange(length, length);
}
}, [autoFocus]);
return <TextareaAutosize {...restProps} ref={textareaRef} />;
}
);