Ire
Ire

Reputation: 45

OnClick calls a function once

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!

Upvotes: 0

Views: 160

Answers (2)

Nero
Nero

Reputation: 51

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

Upvotes: 1

Nudelsuppe_42_
Nudelsuppe_42_

Reputation: 54

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}

Upvotes: 0

Related Questions