最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Thousand separator input with React Hooks - Stack Overflow

programmeradmin4浏览0评论

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

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>
    );
}
Share Improve this question edited Jul 25, 2020 at 19:47 asked Jul 25, 2020 at 17:22 user10823960user10823960 1
  • 1 You can refer to react documentation: reactjs.org/docs/hooks-state.html on the first example shows you how to use onChange (onClick on their example) and useState hook – boertel Commented Jul 25, 2020 at 17:26
Add a comment  | 

1 Answer 1

Reset to default 23

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>

发布评论

评论列表(0)

  1. 暂无评论