Search code examples
reactjsreact-hooksstatecounterref

React counter does not increment when taking the number from an input


React counter the "+" and "-" buttons does not increment when taking the number from an input it just adds 1111111 but decrement normally. also the "+" and "-" buttons work normally if user didn't insert number from input. here is my code :

 import React, { useState } from "react";
import { useRef } from "react";

function App() {
  var [count, setCount] = useState(0);
  function handleClick() {
    setCount(inputRef.current.value);
  }

  function decrease() {
    setCount(count - 1);
  }
  function increase() {
    setCount(count + 1);
  }
  const inputRef = useRef(null);

  
  return (
    <div className="container">
      <input ref={inputRef} type="text" id="message" name="message"></input>
      <button onClick={handleClick}>Enter</button>
      <h1>{count}</h1>
      <button onClick={decrease}>-</button>
      <button onClick={increase}>+</button>

    </div>
  );
}
export default App;

Solution

  • This is because inputRef.current.value is a string and this means + will be a concatenation operation between a string and a number. JavaScript will therefore cast the number to string in decrease() and increase() functions, thus resulting in an output like 111...

    To fix this, please cast the input value to a number:

    var [count, setCount] = useState(0);
    function handleClick() {
      setCount(+inputRef.current.value);
    }
    

    Notice the + operator, this will convert the input value to a number. If you want to parse to an integer or a float, you may want to use parseInt(inputRef.current.value) or parseFloat(inputRef.current.value) respectively.