I’m trying to add commas to a text input as the user types.
- User typing: 1234
- Rendered Input value: 1,234
However, I’m encountering two issues.
-
React doesn’t allow updating e.target.value before setState (https://react.dev/reference/react-dom/components/input#my-input-caret-jumps-to-the-beginning-on-every-keystroke)
-
If I ignore React’s advice and update e.target.value directly, the cursor moves to the end even when typing in the middle of the text.
import {useState} from 'react';
const NumberInput = () => {
const [value, setValue] = useState('');
const handleChange = (event) => {
const inputValue = event.target.value;
setValue(
inputValue.replace(/D/g, '').replace(/B(?=(d{3})+(?!d))/g, ',')
);
};
return <input type="text" value={value} onChange={handleChange} />;
};
export default NumberInput;
Is there a good approach to adding commas in a controlled component? I would appreciate any suggestions or solutions. Thank you!
2
Answers
Asking ChatGPT about this he provided the following approach, Please read the notice at the bottom since there is a catch and it might not be suitable for you
it basically makes sure that the cursor is set in the right place after every user input, At first I thought it gets the job done perfectly, Though I noticed that it actually glitches when the user presses two buttons at nearly the same time, It’s unlikely that users will do that but if that’s a real concern you might need a different approach.
your code look pretty, if you want to try more i’ll give you some option.