0
class Todo extends Component {
  constructor(props) {
    super(props);
    this.state = {
      amount:1000000
    }
   }
  handleChange= (e)=> {
    const number= Number(e.target.value).toLocaleString();
    console.log(number);
    this.setState({
      amount: number
    })
  }
  render() {
    return (
      <div>
       <input onChange={this.handleChange} value={this.state.amount.toLocaleString()}/>
      </div>
    )
  }
}

ReactDOM.render(<Todo />, document.getElementById('root'));

I am a new front end developer. I am unable to change the value of my textbox with more than 9,999. I get NaN

https://codesandbox.io/s/y2lrywpk21

1
  • Your code sandbox doesn't appear to match your question. Commented Mar 24, 2020 at 20:48

2 Answers 2

1

The problem is once you get into the thousands, you introduce commas. The comma is causing an issue when you try to convert it to a number. Use this to strip the commas: .replace(/,/g, '').

You should also only use .toLocalString when displaying the value. There's no need to use it when setting state and when reading state.

Working example:

class Todo extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      amount:1000000
    }
   }
  handleChange= (e)=> {
    const number= Number(e.target.value.replace(/,/g, ''));
    console.log(number);
    this.setState({
      amount: number
    })
  }
  render() {
    return (
      <div>
       <input onChange={this.handleChange} value={this.state.amount.toLocaleString()}/>
      </div>
    )
  }
}

ReactDOM.render(<Todo />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"/>

Sign up to request clarification or add additional context in comments.

1 Comment

Thank You for explaining me the issue. Works now
0

Why are you using toLocaleString?

toLocaleString is used to translate a number into language specific formats i.e. using commas when dealing with US English or using decimals when dealing with German language and other European languages. 3,000 vs 3.000 for example.

Check out the documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString

I think you’re misusing toLocaleString. Also, check out the disclaimer at the bottom of the docs pertaining to using this function with large numbers.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.