0

How can I modify it to allow to enter arbitrary values in 'input' and bring the button value into 'input'? If the user presses the +1 button while entering 3, the value in 'input' increases by 1 from 3. And I hope he can delete the "input" value without the "delete" button.
Also, I want to set the default value to zero and let only positive numbers enter from zero. plz help me.
This is my code.

input-button.jsx

import React , { useState } from "react";

const PlusButton = () => {
  const [cnt, setCnt] = useState(0);

  const onIncrease = () => {
    setCnt(prevCnt => prevCnt + 1);
  }

  const onIncrease2 = () => {
    setCnt(prevCnt => prevCnt + 10);
  }

const onIncrease2 = () => {
    setCnt(prevCnt => prevCnt + 100);
  }
  return(
    <>
      <div>
        <input type="number" min='0' placeholder='Click button or Enter a random value' value={cnt}/>
      </div>
        
      <button onClick={onIncrease}>+1</button>
      <button onClick={onIncrease2}>+10</button>
      <button onClick={onIncrease2}>+100</button>
    </>
  );
}

export default PlusButton;

(Note. I'm going to import this file to another file. like <PlusButton/>)

Glitt
  • 19
  • 5

1 Answers1

0

Add onChange to the input.

 const onChange = (e) => {

    if (e.target.value === '') {
      setCnt(0)
      return;
    }
    if (e.target.checkValidity()) { //check if min=0
      setCnt(parseInt(e.target.value)) // allow only whole numbers using parseInt.
    }
 }

 const onIncrease = (value) => setCnt(prevCnt => prevCnt + value);
 

  <input type="number" onChange={onChange} min='0' placeholder='Click button or Enter a random value' value={cnt}/>

  <button onClick={() => onIncrease(1)}>+1</button>
  <button onClick={() => onIncrease(10)}>+10</button>
  <button onClick={() => onIncrease(100)}>+100</button>
Someone Special
  • 12,479
  • 7
  • 45
  • 76
  • Thank you! But if I try to erase the value entered in "input", the number of work digits will not be erased. If I input 1234, 234 is erased and the 1 remains. Could I know why this is happening? – Glitt Feb 09 '22 at 04:57
  • added some modifications to the code to check for empty string. You can either setCnt(0) or setCnt(''), your choie. – Someone Special Feb 09 '22 at 05:00
  • 1
    Thank you very very much. Thanks to this, the problem that bothered me for a few days was solved. – Glitt Feb 09 '22 at 06:40