Skip to content

Instantly share code, notes, and snippets.

@shijiatongxue
Created December 13, 2021 16:41
Show Gist options
  • Save shijiatongxue/992cf9c9f8fc4a9d8d708fb93a987472 to your computer and use it in GitHub Desktop.
Save shijiatongxue/992cf9c9f8fc4a9d8d708fb93a987472 to your computer and use it in GitHub Desktop.
import React, { useState, useRef, useEffect } from "react";
/**
* Solution: fix controlled input cursor lossing
* https://github.com/facebook/react/issues/955
*/
export default function App() {
const inputRef = useRef();
const [value, setValue] = useState("12345678");
const [selection, setSelection] = useState({
start: value.length,
end: value.length
});
const [insertFlag, setInsertFlag] = useState(1);
const maxLength = 8;
const onChange = (e) => {
let newValue = e.target.value;
const start = inputRef.current.selectionStart;
const end = inputRef.current.selectionEnd;
if (newValue.length > maxLength && value.length === maxLength) {
const len = newValue.length - value.length;
// do noting
setSelection({ start: start - len, end: end - len });
setInsertFlag(insertFlag + 1);
} else {
setValue(newValue);
}
};
useEffect(() => {
inputRef.current.selectionStart = selection.start;
inputRef.current.selectionEnd = selection.end;
}, [insertFlag]);
return (
<div className="App">
<input ref={inputRef} value={value} onChange={onChange} />
</div>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment