Ben
Ben

Reputation: 1

Why is this button requiring 2 clicks to revert state in ReactJS?

I want to click back and forth between pressed and not pressed for a button. But when pressed, requires 2 clicks to revert back to not pressed.

const [priority, setPriority] = useState('');
var isPriority = 0;

function swapPriority() {
    if (isPriority === 0) {
        setPriority("btn__danger");
        isPriority = 1;
    } else {
        setPriority("");
        isPriority = 0;
    }
}

const template = {
 <button
      type="button"
      className={'btn ' + priority}
      onClick={swapPriority}
 >
}

Upvotes: 0

Views: 104

Answers (2)

M-Raw
M-Raw

Reputation: 839

you're defining priority and changing isPriority the react way would be like this:

const [priority, setPriority] = useState(false);

function swapPriority() {
 setPriority(!priority);
}

const template = {
 <button
  type="button"
  className={priority ? 'btn btn__danger' : 'btn '}
  onClick={swapPriority}
 >{priority ? 'danger' : 'not-danger'}</button>
}

Upvotes: 0

Hardik3296
Hardik3296

Reputation: 456

In your code basically when you click the first time you set priority to "btn_danger" and isPriority to 0. But isPriority is a normal variable so when the code re-renders, it again sets isPriority to 0 (although you set it to 1 previously, since value of normal variable does not persists between renders). Now when you click again, the if condition is true (since isPriority is 0) so it executes setPriority(). But since there is no change in the value inside setPriority() so no re-render occurs and the isPriority is set to 1. Again when you click the button, since isPriority is now 1 it behaves as you expect. As @M-Raw suggested above this is not the right way to handle this thing. (But it is a great way to understand how react works nontheless.)

Upvotes: 2

Related Questions