Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

189
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda