'How to re-render React Input with formatted value after user put each character with OnChange
I have react input component that should only take number and commas. I was able to restrict users from inserting character, also I was able to get the numbers with commas in the useState. But I want to show commas in the input even though the users don't put them. For example, if a user put 100000, the input will automatically re-render to 100,000 in every onChange.
Below is my code:
const regex = new RegExp("^[0-9,]*$");
const [homePrice, setHomePrice] = useState( "100,000");
const onChangeHomePrice = (e) => {
setHomePrice(e.target.value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","));
console.log(homePrice);
};
return (
<FormInput type="text" maxLength={10} value = {homePrice} placeholder="100,000"
onChange={onChangeHomePrice}
onKeyPress={(e) => {
if (!regex.test(e.key)) {
e.preventDefault();
}
}}
>
</FormInput>
)
How can I re-render the input with proper commas? In my code, when I put console.log(homePrice), I can see the commas. So, I put homePrice as input value :
value={homePrice}.
But this does not change the user input with proper commas.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
