React & TypeScript, getting errors when adding conditionally onClick prop

Viewed 65

I want to conditionally 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 ?

1 Answers

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>
)}
Related