Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

188
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda