Reset cursor to the start on <textarea> React

401 Views Asked by At

i have a textarea in react that i want to create and i want the cursor the start at the beginning when it loses focus. How do i solve this issue?

codesandbox: https://codesandbox.io/s/affectionate-tu-2cd6j6?file=/src/App.js

``

export default function App() {
  const textareaRef = useRef();
  return (
    <div>
      <textarea
        ref={textareaRef}
        id="my-text-area"
        defaultValue={"Hello World!"}
        rows="2"
        tabIndex="-1"
        style={{ resize: "none", overflow: "hidden" }}
        onBlur={() => textareaRef.current.setSelectionRange(0, 0)}
      ></textarea>
    </div>
  );
}

tried using onblur function with setSelectionRange but its not working for some reason.

1

There are 1 best solutions below

2
kind user On

Played a bit with your code, seems like you are missing focus() call after changing the selection range.

onBlur={() => {
  textareaRef.current.setSelectionRange(0, 0);
  textareaRef.current.focus();
}}

Then, the cursor will appear at the beginning of the textarea content.

https://codesandbox.io/s/suspicious-tdd-r8t77j?file=/src/App.js