Home > database >  In React JS update value of a input field using button & keyboard
In React JS update value of a input field using button & keyboard

Time:12-22

Following is my react code:

export default function Counter() {
    const [count, setcount] = useState(0);
    const increase = () => {setcount(count   1)};
    const decrease = () => {setcount(count - 1)};
    const manual = (event) => {setcount(event.target.value)}

  return (
    <div>
        <div>
            <button onClick={increase} className='bg-green-700 w-12 border-2'> </button>
            <input onKeyUp={(event) => {manual}} onChange={setcount} value={count} className='border-2 text-center' type="number" name="count" id="count" />
            <button onClick={decrease} className='bg-rose-700 w-12 border-2'>-</button>
        </div>
    </div>
  )
}

I want the input field to get updated by the buttons as well as manually updating the input field using the keyboard.

CodePudding user response:

you need to pass parenthesis to your function:

<input onKeyUp={(event) => manual(event)} onChange={setcount} value={count} className='border-2 text-center' type="number" name="count" id="count" />

CodePudding user response:

Currently if your looking to increment the count value every onKeyUp you can get the event listener by using window.addEventListener("keydown", handleKeyPress) on useEffect and later useCallback to handle setCount .

const [count, setcount] = useState(0);
  const increase = () => {
    setcount(count   1);
  };
  const decrease = () => {
    setcount(count - 1);
  };

  const handleKeyPress = useCallback(
    (event) => {
      setcount(count   1);
    },
    [count]
  );

  useEffect(() => {
    window.addEventListener("keydown", handleKeyPress);

    return () => {
      window.removeEventListener("keydown", handleKeyPress);
    };
  }, [handleKeyPress]);

  return (
    <div>
      <div>
        <button onClick={increase} className="bg-green-700 w-12 border-2">
           
        </button>
        <input
          onChange={setcount}
          value={count}
          className="border-2 text-center"
          type="number"
          name="count"
          id="count"
        />
        <button onClick={decrease} className="bg-rose-700 w-12 border-2">
          -
        </button>
      </div>
    </div>
  );

  • Related