Arttu
Arttu

Reputation: 251

How to change button value on click?

I'm trying to do button which value is set to '' by default and when clicking button it's own value should change. Here is what I tried already.

First I did new hook state which sets value to '':

const [buttonValue, setButtonValue] = useState('');

Then I did event handler which should set new value depending on current value. Value is set '' by default, on click button value should change to value1, click again and value should change to value2, and last when value is set to value2 it should change back to default ''. First time I click button value actually changes to value1 but then value doesn't change anymore:

const valueHandler = (e) => {
  setButtonValue(e.target.value);

  if (e.target.value === '') {
    setButtonValue('value1');
  }
  if (e.target.value === 'value1') {
    setButtonValue('value2');
  }
  if (e.target.value === 'value2') {
    setButtonValue('');
  }
}

And last I did actual button which should change it's own value:

<button value='' onClick={valueHandler}>
  Click to change value
</button>

Any ideas how to make button change it's own value on click? Also if somebody have better solution for this I'm listening :)

Upvotes: 0

Views: 850

Answers (1)

PRSHL
PRSHL

Reputation: 1443

const [buttonValue, setButtonValue] = useState('')

const valueHandler = (e) => {
   if (e.target.value === 'value1') {
      setButtonValue('value2')
   } else {
      setButtonValue('')
   }
}

return (
   <button value={buttonValue} onClick={valueHandler}>
      Click to change value
   </button>
)

You didn't use the buttonValue in the <button> before.

Upvotes: 2

Related Questions