Home > Enterprise >  Single handler for ReactJS onClick and onKeyDown events for TypeScript
Single handler for ReactJS onClick and onKeyDown events for TypeScript

Time:01-01

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?

CodePudding user response:

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.

  • Related