react-use-caret-position
Custom React hook to keep track of the caret position in an input.
Motivation
If there is some side effect/async code in an input's onChange
event handler (e.g. dispatching a Redux action without doing anything else, format text in some way like uppercase, etc), the caret will annoyingly be booted to the end of the input after each keystroke.
react-use-caret-position
fixes this undesirable behavior by keeping track of the caret position and setting it on render.
Example Usage
_22import React, { useState } from 'react';_22import { useCaretPosition } from 'react-use-caret-position';_22_22const Input = () => {_22 const [text, setText] = useState('hello world');_22_22 const { ref, updateCaret } = useCaretPosition();_22_22 const handleChange = e => {_22 // Some side effect in the `onChange` handler (could be anything)_22 const inputToUpperCase = e.target.value.toUpperCase();_22_22 setText(inputToUpperCase);_22_22 // Track the caret position with the hook_22 updateCaret();_22 };_22_22 return <input ref={ref} value={value} onChange={handleChange} />;_22};_22_22export default Input;