score:15

Accepted answer

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>


Related Query

More Query from same tag