score:2

Accepted answer

You should parse the int as the value is getting read from the event.target.value which will always give you string

  handleChange = (e) => {
    const { name, value } = e.target
    this.setState({ [name]: parseInt(value, 10) })
  }

score:0

You can use parseInt when use the setState:

  handleChange = (e) => {
    const { name, value } = e.target
    this.setState({ [name]: parseInt(value) })
  }

But maybe is necessary to valid the value before execute parseInt, because can happen a error like Received NaN for thevalueattribute. If this is expected, cast the value to a string.

So maybe with try/catch can solve your problem:

  handleChange = (e) => {
    const { name, value } = e.target

    try {
      this.setState({ [name]: parseInt(value) })
    } catch (e) {
      this.setState({ [name]: 0})
    }
  }

score:0

class NumberForm extends Component {
  state = {
    myNumber:parseInt('')
  }

  handleChange = (e) => {
    const { name, value } = e.target
    this.setState({ [name]: value })
//this.setState({ [name]: parseInt(value, 10) })
  }

  render() {
    return (
      <form>
        <input
          type="number"
          name="myNumber"
          value={this.state.myNumber}
          onChange={this.handleChange}
        />
      </form>
    );
  }
}

This could works for starting your state and html element in empty

score:0

Here we GO SOLUTION for this problem is you can parse the value of state in handler function.

 const handleChange = (event) => {
       
        this.setState({ [event.target.name]: parseInt(event.target.value, 10) })
      }

Related Query

More Query from same tag