react-use-caret-position

Custom React hook to keep track of the caret position in an input.

Built with:
  • react
  • typescript

npm (scoped)

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


_22
import React, { useState } from 'react';
_22
import { useCaretPosition } from 'react-use-caret-position';
_22
_22
const 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
_22
export default Input;