react-textarea-autosize icon indicating copy to clipboard operation
react-textarea-autosize copied to clipboard

Cursor not at the end of input when using autofocus with initial value

Open ArnaudBarre opened this issue 3 years ago • 1 comments

Repro: https://stackblitz.com/edit/vitejs-vite-b4qb54?file=src%2FApp.jsx&terminal=dev

Temporary solution: Uncomment FixedTextarea line

ArnaudBarre avatar Jun 07 '22 10:06 ArnaudBarre

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} />;
  }
);

AielloChan avatar Aug 11 '25 06:08 AielloChan