Saturday, May 25, 2024
 Popular · Latest · Hot · Upcoming
97
rated 0 times [  100] [ 3]  / answers: 1 / hits: 9348  / 4 Years ago, sat, july 25, 2020, 12:00:00

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>
);
}

More From » reactjs

 Answers
29

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>




[#3072] Thursday, July 23, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
victorr

Total Points: 193
Total Questions: 86
Total Answers: 105

Location: Pitcairn Islands
Member since Thu, Jun 24, 2021
3 Years ago
victorr questions
Fri, Nov 13, 20, 00:00, 4 Years ago
Thu, Jun 11, 20, 00:00, 4 Years ago
Mon, Aug 19, 19, 00:00, 5 Years ago
;