npm

Need private packages and team management tools?Check out npm Orgs. »

react-use-caret-position

1.0.1 • Public • Published

🎣
react-use-caret-position

CircleCI (all branches) npm (scoped) code style: prettier All Contributors

Motivation

screencap

When working on a project, I came across an interesting case where the input was losing its caret position after each change. I realized it was happening if there was some sort of side effect in the onChange handler. In my case, I was dispatching a Redux action on change and nothing else, but the side effect could be anything, really.

react-use-caret-position attempts to fix that by keeping track of the caret position and setting it on render.

Install

With npm...

npm install react-use-caret-position

With yarn...

yarn add react-use-caret-position

Usage

const caret = useCaretPosition(inputRef);
const { start, end, updateCaret } = caret;

Like so...

import React, { useState } from 'react';
import { useCaretPosition } from 'react-use-caret-position';
 
const Input = () => {
  // Some sort of input state
  const [text, setText] = useState('hello world');
 
  // Track the caret position with the hook
  const { ref: inputRef, updateCaret } = useCaretPosition();
 
  const handleChange = e => {
    // Some sort of side effect in the onChange handler
    // which normally makes the input lose its position
    const inputToUpperCase = e.target.value.toUpperCase();
    setText(inputToUpperCase);
 
    // `updateCaret` will update the selectionStart and selectionEnd
    // values of the input
    updateCaret();
  };
 
  return (
    <input 
      ref={inputRef} 
      value={value} 
      onChange={handleChange} 
    />
  );
};
 
export default Input;

API

Return Object

Key Description
ref React.RefObject that should be assigned to your input
start number containing the current state of selectionStart
end number containing the current state of selectionEnd
updateCaret function which updates both caret states

Thanks ❤️

License

MIT © melanieseltzer

Contributors ✨

Thanks goes to these wonderful people (emoji key):

Aaron Ross
Aaron Ross

💻 📖

This project follows the all-contributors specification. Contributions of any kind welcome!

Keywords

none

install

npm i react-use-caret-position

Downloadsweekly downloads

1

version

1.0.1

license

MIT

homepage

github.com

repository

Gitgithub

last publish

collaborators

  • avatar
Report a vulnerability