I want to conditionnally add an onClick function to my TypeScript React component like so
<div onClick={(!disabled && onClick) ?? undefined}>{children}</div>
But I get this error :
Type 'false | (() => void) | undefined' is not assignable to type 'MouseEventHandler<HTMLDivElement> | undefined'. Type 'boolean' is not assignable to type 'MouseEventHandler<HTMLDivElement>'.
My onClick prop variable is of type onClick?: () => void; in my props interface.
What should I do ?
Thanks by advance !
As onClick is typed, an easy way to avoid those type errors is to do as below. Notice I'm not passing onClick directly, as type () => void wouldn't be assignable to the click handler.
{!disabled && onClick ? (
<div onClick={(e) => onClick()}>{children}</div>
) : (
<div>{children}</div>
)}