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/>
)
CodePudding user response:
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>