React: Button value gets read as string?

I’m currently working on the Pomodoro challenge but have gotten stuck passing a function parameter on a button.

I’ve passed the value of the object state.sessionTime along with the button as a value. It gets read as a value, but treated as a string? Result is although the value is 8000 no calculation will work on it.

Here’s the button:
<button value={this.state.sessionTime} onClick={this.add} >+</button>

and here’s the function:

   add = (e) => {
      var subType = e.currentTarget.value;
      this.setState((prevState,props) => ({
       subType: prevState.subType +1000
     console.log(subType); //Output is "8000" instead of 9000

There were no errors in the console log

Uhm, do you have a link for us? So we can see tinker a bit with the real code ^^

Anyway,one thing: you log subtype ( which is the current target value ) and not this.state.subtype which is the state status^^
You should also call it in a callback since setState is async^^
Oh, and you do not use the current target value ( or the prevstate subtype) ^^ Dunno which is correct,

I believe that the DOM value is always treated as string.

In this case you have different options to achieve what you are asking:

  1. onClick calls an anonimous function that return the class method:
<button onClick={() => this.add(10)} >+</button>

add = n => console.log(n) // 10
  1. More “reacty”. Since your button value is bound to state, you can remove it entirely and simply compute from state
<button onClick={this.add} >+</button>

state = {
  val: 10,
add = () => {
  this.setState((prevState) => ({ val: prevState + 10}) 
} // async update val to 20. next time you click -> 30 -> 40 ...

Hope it helps :+1:

1 Like