Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do you I React to get the button value into the input?

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/>)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading