-
Hi guys, https://codesandbox.io/s/suspicious-lovelace-x5tjjl?file=/src/App.js if there is something that you think missing, let me know. I'll add more information. Thanks in advance. :) |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
Instead of format the number value by using "onInput", you should use "onBlur" to only format the value after end-user finished typing. Another solution is to use debounce to wait until typing is ended to trigger formatting. This is the easiest way to handle input with formatting and avoid to messing around with input selection (input caret |
Beta Was this translation helpful? Give feedback.
-
<input
type="text"
{...register(`price`, {
setValueAs: (value: string) => value.replaceAll(",", ""),
})}
{...numberInputProps((formattedValue) =>
setValue("price", formattedValue, {
shouldDirty: true,
}),
)}
/> import React from "react";
type Type = {
onKeyDown: React.KeyboardEventHandler<HTMLInputElement>;
onChange: React.ChangeEventHandler<HTMLInputElement>;
};
export const numberInputProps = (callback: (formattedValue: string) => void): Type => {
return {
onKeyDown: (e) => {
const okKey = ["Tab", "Backspace", "ArrowLeft", "ArrowRight"].some((key) => e.key === key);
if (!okKey && Number.isNaN(Number(e.key))) {
e.preventDefault();
}
},
onChange: (e) => {
const { value } = e.target;
const numberValue = value.replace(/,/g, "");
if (!isNaN(Number(numberValue)) && Number.isFinite(+numberValue)) {
const formattedValue = Number(numberValue).toLocaleString("ko-Kr");
callback(formattedValue);
}
},
};
}; |
Beta Was this translation helpful? Give feedback.
@daheejo
Instead of format the number value by using "onInput", you should use "onBlur" to only format the value after end-user finished typing. Another solution is to use debounce to wait until typing is ended to trigger formatting. This is the easiest way to handle input with formatting and avoid to messing around with input selection (input caret
|
) and its value.Example: https://input-number.vercel.app/demo/precision