Search code examples
reactjstypescriptinputtextinputtext-cursor

How to solve the issue of a text cursor in a text input being automatically placed at the end of the input after a typed character has been inserted?


I stumbled upon this bug which looks annoyingly simple to solve. This is the code sandbox, I believe it is pretty small.

I put the code too here for easier answering.

I expected this to work since it is very simple and I have experience with React of about some months. Just a normal monitored-for-changes input. There are no error messages, just an unusual behavior.

I've tried to search on StackOverflow but I found only old questions with answers that looked like hacks, such as using onKeyUp instead of onChange and defaultValue instead of value.

import { ChangeEvent, useEffect, useState } from "react";
import "./styles.css";

const ObservationsField = ({
  onChange,
  value
}: {
  onChange: (ev: ChangeEvent<HTMLInputElement>) => void;
  value: string;
}) => {
  const [crtVal, setCrtVal] = useState("");

  useEffect(() => {
    setCrtVal(value);
  }, [value]);

  return <input onChange={onChange} value={crtVal} defaultValue={value} />;
};

export default function App() {
  const [x, setX] = useState("");

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <ObservationsField
        onChange={(ev) => {
          setX(ev.target.value);
        }}
        value={x}
      />
    </div>
  );
}

Solution

  • I change the input tag in ObservationsField

    return <input type="text" onChange={onChange} value={crtVal} />;
    

    https://codesandbox.io/s/charming-neumann-6wnw4?file=/src/App.tsx
    x is binding with the input. What would you expect?