1.1.0 • Published 2 years ago

react-use-caret-position v1.1.0

Weekly downloads
54
License
MIT
Repository
github
Last release
2 years ago

npm (scoped) code style: prettier All Contributors

Live demo: https://react-use-caret-position.netlify.app

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.

Install

With npm...

npm install react-use-caret-position

With yarn...

yarn add react-use-caret-position

Usage

import React, { useState } from 'react';
import { useCaretPosition } from 'react-use-caret-position';

const Input = () => {
  const [text, setText] = useState('hello world');

  const { ref, updateCaret } = useCaretPosition();

  const handleChange = e => {
    // Some side effect in the `onChange` handler (could be anything)
    const inputToUpperCase = e.target.value.toUpperCase();

    setText(inputToUpperCase);

    // Track the caret position with the hook
    updateCaret();
  };

  return (
    <input 
      ref={ref}
      value={value} 
      onChange={handleChange} 
    />
  );
};

export default Input;

API

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

Return Object

KeyTypeDescription
refReact.RefObjectRef that should be assigned to your input
startnumberCurrent start position of the text selection
endnumberCurrent end position of the text selection
updateCaret() => voidFunction to set the caret position

License

MIT © melanieseltzer

Contributors ✨

Thanks goes to these wonderful people (emoji key):

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

1.1.0

2 years ago

1.0.3-beta.0

3 years ago

1.0.3

3 years ago

1.0.2

3 years ago

1.0.1

5 years ago

1.0.0

5 years ago