Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

252
Views
Conditionally add onClick prop React Typescript

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 !

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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>
)}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!