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

186
Views
Single handler for ReactJS onClick and onKeyDown events for TypeScript

I am trying to add onKeyPress handlers to my application to make it a11y-compliant. I have some interactive <div /> elements, where it is presenting a problem.

I have the following event handlers to I want to fire on click.

const handleViewInfoClick = (event: MouseEvent<HTMLDivElement> | KeyboardEvent<HTMLDivElement>): void => {
  event.preventDefault();
  onProfileClick();
  window.open(withConfig(ConfigEnum.PROPERTY_PROFILE_URL, { propertyID: communityId }), '_blank');
};

I am using the above hanlder as:

<div
  className={classes.community_name}
  onClick={handleViewInfoClick}
  onKeyDown={(e) => {
    if (e.keyCode === 13) {
      handleViewInfoClick(e);
    }
  }}
  tabIndex={0}
  role="button"
>

It results in typescript errors.

If I declare event as (event: MouseEvent | KeyboardEvent), typescript complaints that handleViewInfoClick(e) is getting a wrong type for an argument. If I declare KeyboardEvent<HTMLDivElement>, the handleViewInfoClick(e) is not raising errors. However, typescript complaints that Type 'KeyboardEvent<HTMLDivElement>' is not generic.

What is the correct way to handle this?

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

0

With React handlers, you should use the event typings from React, not from the DOM:

const handleViewInfoClick = (event: React.KeyboardEvent<HTMLDivElement> | React.MouseEvent<HTMLDivElement>): void => {

You could also use

const handleViewInfoClick = (event: React.SyntheticEvent) => {

because both KeyboardEvent and MouseEvent inherit from SyntheticEvent, and all you care about is being able to call preventDefault on it, which SyntheticEvent has.

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!