I want to add thousand separators to an number input however I don't want to change the value. I add the separators but the value will become string.
import "./styles.css";
import { useState } from "react";
export default function App() {
const [value, setValue] = useState(0);
const addCommas = (num) =>
num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
const removeNonNumeric = (num) => num.toString().replace(/[^0-9]/g, "");
const handleChange = (event) =>
setValue(addCommas(removeNonNumeric(event.target.value)));
console.log(typeof value)
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
<input type="text" value={value} onChange={handleChange} />
</div>
);
}
In this code as soon as user enters a number, the typeof value will become string since we are using toString method. I was wondering if there is a way to implement an input and only modify its view not its value.