Home > Software engineering >  Unable to use ternary operator (?) in TypeScript (Next.js)
Unable to use ternary operator (?) in TypeScript (Next.js)

Time:10-25

Im currently trying to setup a ternary operator condition in my onClick event in Next.js. But im getting an error saying my condition is returning nothing. Please help...

enter image description here

enter image description here

CodePudding user response:

The onClick handler expects a function, not a function call. Just add an arrow function that calls the alert.

onClick={... ? () => alert('...') : addToCardList};

CodePudding user response:

You correctly included the addToCart as a function by not calling it.

The problem is that you did not do the same for alert. Your alert is called while rendering, so you are trying to set the onClick function to the return of the alert call.

Replace alert("aaaaa") with () => alert("aaaaaa") to wrap it in a function

  • Related