Search code examples
reactjssetstate

ReactJS - SetState does not update the state when the state variable is a number


I have a reset button which sets the state of all input fields(controlled) to initial state. This works well with with all numbers except for the following scenario:

If Input is 0040, clicking restore does not reset it to 40. This may work if it is a string, but is there a way to update it if the state variable is a number.

class Example extends React.Component {
  state = {
    code1: 40,
    code2: 60,
    code3: 70,
  }
  
  handleChange = (e) => {
    this.setState({ [e.target.name]: e.target.value });
  }
  
  handleReset = () => {
    this.setState({
      code1: 40,
      code2: 60,
      code3: 70,
    });
  }

  render() {
    return (
      <div>
        <div>
          <input 
            type="number" 
            name="code1"
            value={this.state.code1} 
            onChange={this.handleChange} 
            min="0" 
            max="100" 
          />
        </div>
        <div>
          <input 
            type="number" 
            name="code2"
            value={this.state.code2} 
            onChange={this.handleChange} 
            min="0" 
            max="100" 
          />
        </div>
        <div>
          <input 
            type="number" 
            name="code3"
            value={this.state.code3} 
            onChange={this.handleChange} 
            min="0" 
            max="100" 
          />
        </div>
        <button onClick={this.handleReset}>Reset</button>
      </div>
    )
  }
}

ReactDOM.render(<Example/>, 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" />


Solution

  • You may want to use toString() for your input value rather than storing String in state. Try this demo

    render() {
    return (
      <div>
        <div>
          <input
            step="1"
            type="number" 
            name="code1"
            value={this.state.code1.toString()} 
            onChange={this.handleChange} 
            min="0" 
            max="100" 
          />
        </div>
        <div>
          <input 
            type="number" 
            name="code2"
            value={this.state.code2.toString()} 
            onChange={this.handleChange} 
            min="0" 
            max="100" 
          />
        </div>
        <div>
          <input 
            type="number" 
            name="code3"
            value={this.state.code3.toString()} 
            onChange={this.handleChange} 
            min="0" 
            max="100" 
          />
        </div>
        <button onClick={this.handleReset}>Reset</button>
      </div>
    )
    }