Home > Software engineering >  OnClick calls a function once
OnClick calls a function once

Time:03-30

I have a button that is expected to call a function onClick. The function is being passed in as a prop. And this is what it looks like:

onClick={() => handleError && handleError()}

The problem here is that when I click on it, it only gets called once and doesn't get called again after that.

This is the handleError function, but the problem isn't the content of the function. It is that the function isn't being called at all after it has been called once:

  const handleError = (nextBtn: BtnItem) => {
    if (title === '') {
      setError(true);
    } else {
      if (nextBtn?.onClick) {
        nextBtn.onClick();
        console.log('clicked too');
      } else if (nextBtn?.route) {
        history.push(nextBtn.route);
        console.log('clicked');
      }
    }
  };

Any ideas why this might be happening? Any help will be appreciated. Thank you!

CodePudding user response:

onClick={handleError ? () => handleError() : () => {}}

CodePudding user response:

Whats handleError? We need a bit more code to work with.

If you only want to execute the function if a variable is true. You can check it directly in the method you call and not in the onClick() itself.

Just do onClick={handleError}

  • Related