1

I am using a <button> in a React component that has onClick and disabled attributes. The onButtonClick action and isButtonDisabled variable are retrieved from the store (I use Zustand). The isButtonDisabled selector includes some logic to determine whether the button should be disabled or not. My expectation is that the React component will disable the button using this variable, and only call onClick when the button is not disabled. However, it's possible that the component may not disable the button and call onButtonClick even when the button should be disabled.

This raises the question of whether I should run the same logic in the onButtonClick action and check if the button should be disabled. If the button is disabled, should I simply return early and do nothing?

This would be useful in cases where we forget to set the disabled attribute on a button and execute that action. Do I need to run the same logic that calculates whether the button should be disabled again in the action, or is it enough to trust the component to set disabled and use isButtonDisabled on a button?

export const Component: React.FC = () => {
  // Zustand store, it calls a selector that runs some logic.
  const isBtnDisabled = useAppState(`isBtnDisabled`);
  const { onBtnClick } = useActions();


  return (
      <Button onClick={onBtnClick} isDisabled={isBtnDisabled}>
        Delete Layer
      </Button>
  );
}
TylerH
  • 20,799
  • 66
  • 75
  • 101
ellis
  • 181
  • 10
  • 1
    If you have a category of these buttons which should be disabled during the action, then it would make sense to make `isDisabled` a required prop (either on `Button` or on some specialised `Button` that is compatible with these actions). Doing the check again in the action is a bit of runtime boilerplate that can be avoided by a little light typescript :-) – motto Feb 16 '23 at 08:42

1 Answers1

1

You can trust react to disable the button for you.

But don't forget that taking away the HTML disable property is super easy, any teen these days know how to open the HTML elements and erase the disable property. So protecting your onClick function might be a good option if it's something crucial, obviously it depends in which environment you are planning to deploy.

derFrosty
  • 550
  • 3
  • 17