Home > other >  How can I create a counter inside an input? (react)
How can I create a counter inside an input? (react)

Time:11-12

I would like my counter to update every time the icon is clicked through a function.

import * as C from './styles';

const Cart = () => {
    const addAmountCart = (cont) => {
        return cont   1;
    }

    const [amount, setAmount] = useState(1);


  return (
    <C.Container>
      <input type="text" value={amount}  onChange={e => setAmount(e.target.value)}/>
      <AddCircleOutlineIcon id='add' onClick={addAmountCart(amount)}/>
    </C.Container>
  )
}

export default Cart;

CodePudding user response:

There are two things you are missing here,

  1. updating state when you click on the button
  2. wrongly written onClick (You were passing executed function, rather than having a function definition assigned as click event handler).

import * as C from './styles';

const Cart = () => {
    const [amount, setAmount] = useState(1);
    const addAmountCart = () => {
        setAmount(amount   1);
    }


  return (
    <C.Container>
      <input type="text" value={amount}  onChange={e => setAmount(e.target.value)}/>
      <AddCircleOutlineIcon id='add' onClick={() => addAmountCart()}/>
    </C.Container>
  )
}

export default Cart;

  • Related