Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React inputs - maintaining cursor positions when updating inputs

I have created an input that adds thousand separators to characters entered by users. I have implemented code to prevent the cursor from repositioning itself at the end of the input when the code adds or removes a thousand separator. However, when the cursor is placed directly before or after a thousand separator, pressing the delete or backspace key respectively does not delete the character. How can I modify my code to enable this functionality?

Additionally, is there a concise way of creating an input with these features in React?

My code is as follows:

import React, { useState, useRef } from 'react';

const NumericInput = () => {
  const [value, setValue] = useState('');
  const inputRef = useRef(null);

const onKeyDown = (e) => {
  const inputElement = inputRef.current;
  const caretStart = inputElement.selectionStart;
  const caretEnd = inputElement.selectionEnd;

  if (e.key === 'Backspace' && caretStart === caretEnd && caretStart > 0) {
    const previousChar = inputElement.value.charAt(caretStart - 1);
    if (previousChar === ',' || previousChar === ' ') {
      e.preventDefault();
      inputElement.setSelectionRange(caretStart - 1, caretEnd - 1);
      return;
    }
  }

  if (e.key === 'Delete' && caretStart === caretEnd && caretEnd < inputElement.value.length) {
    const nextChar = inputElement.value.charAt(caretStart);
    if (nextChar === ',' || nextChar === ' ') {
      e.preventDefault();
      inputElement.setSelectionRange(caretStart + 1, caretEnd + 1);
      return;
    }
  }

  if (!/^-?\d*$/g.test(value) && e.key !== '-' && e.key !== 'Backspace') {
    e.preventDefault();
  }
};

  const onChange = (e) => {
    const inputValue = e.target.value.replace(/[^0-9-]/g, '');
    setValue(inputValue);

    const inputElement = inputRef.current;
    const caretPosition = Math.max(0, inputElement.selectionStart + (formatValue(inputValue).match(/,/g) || []).length - (formatValue(value).match(/,/g) || []).length);
    inputElement.value = formatValue(inputValue);
    inputElement.setSelectionRange(caretPosition, caretPosition);
  };

  const formatValue = (value) => (value ? value.replace(/\B(?=(\d{3})+(?!\d))/g, ',') : '');

  return (
      <input
        ref={inputRef}
        placeholder='Type Number'
        type='text'
        onKeyDown={onKeyDown}
        onChange={onChange}
        value={formatValue(value)}
      />
  );
};

export default NumericInput;

Any help would be appreciated. Thanks!

like image 361
Digitalwolf Avatar asked Jun 15 '26 04:06

Digitalwolf


1 Answers

You mean like this?

import React, { useState, useRef } from 'react';

const NumericInput = () => {
  const [value, setValue] = useState('');
  const inputRef = useRef(null);

  const onKeyDown = (e) => {
    const inputElement = inputRef.current;
    const caretStart = inputElement.selectionStart;
    const caretEnd = inputElement.selectionEnd;

    if (e.key === 'Backspace' && caretStart === caretEnd && caretStart > 0) {
      const previousChar = inputElement.value.charAt(caretStart - 1);
      if (previousChar === ',' || previousChar === ' ') {
        inputElement.setSelectionRange(caretStart - 1, caretEnd - 1);
        return;
      }
    }

    if (e.key === 'Delete' && caretStart === caretEnd && caretEnd < inputElement.value.length) {
      const nextChar = inputElement.value.charAt(caretStart);
      if (nextChar === ',' || nextChar === ' ') {
        inputElement.setSelectionRange(caretStart + 1, caretEnd + 1);
        return;
      }
    }
  };

  const onChange = (e) => {
    const inputValue = e.target.value.replace(/[^0-9-]/g, '');
    setValue(inputValue);

    const inputElement = inputRef.current;
    const caretPosition = Math.max(0, inputElement.selectionStart + (formatValue(inputValue).match(/,/g) || []).length - (formatValue(value).match(/,/g) || []).length);
    inputElement.value = formatValue(inputValue);
    inputElement.setSelectionRange(caretPosition, caretPosition);
  };

  const formatValue = (value) => (value ? value.replace(/\B(?=(\d{3})+(?!\d))/g, ',') : '');

  return (
    <input
      ref={inputRef}
      placeholder='Type Number'
      type='text'
      onKeyDown={onKeyDown}
      onChange={onChange}
      value={formatValue(value)}
    />
  );
};

export default NumericInput;

But this library seems to work well:

https://www.npmjs.com/package/react-number-format

import { NumericFormat } from "react-number-format";

export default function MainComponent() {
  return (
    <NumericFormat
      thousandSeparator={true}
    />
  );
};
like image 62
Paulo Fernando Avatar answered Jun 16 '26 18:06

Paulo Fernando