I would like to add on a input a thousand separator using React Hooks but I'm not sure how. I have tried the below code so far and is not working.
Can you please point out what could be the issue and how can I implement this?
Thank you.
const MainComponent = () => {
const [value, setValue] = useState(0);
const numberWithComma = () => {
return (+value).toFixed(2).replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,')
}
return (
<div>
<input
type="number"
onChange={numberWithComma}
placeholder="0"
/>
</div>
);
}
You want a controlled form input, so one which gets given a value, and an onInput handler.
You also need it to be a type="text" to allow for the commas to be added, or Chrome will not allow you to set that. However, then to prevent non-numeric chars being added you need another function to strip them out before setting the value.
See the below working snippet:
const {useState} = React;
const MainComponent = () => {
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)));
return (
<div>
<input type="text" value={value} onInput={handleChange} />
</div>
);
};
// Render it
ReactDOM.render(
<MainComponent/>,
document.getElementById("react")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="react"></div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With