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

104
Visualizações
Which is the best way to define the type of dynamic data-attributes in a React component?

I need a React prop to deal with all possible html attributes of an HTML div element part of a React component, but I'm having an issue with Typescript strictness vs React possibilities.

Here the component:

import React from 'react'

type DivAttrs = {
  container?: React.HTMLAttributes<HTMLDivElement>
}

...

<div {...divAttributes?.container}>

And here the prop const provided to the component:

const divAttributes: DivAttrs = {
  container: {
    'aria-describedby': 'test',
    'data-custom-attribute': 'test',
    'data-random-attribute': 'test',
    id: 'test'    
  }
}

The props data-custom-attribute and data-random-attribute give these errors

(property) 'data-custom-attribute': string
Type '{ 'aria-describedby': string; 'data-custom-attribute': string; 'data-random-attribute': string; id: string; }' is not assignable to type 'HTMLAttributes<HTMLDivElement>'.
  Object literal may only specify known properties, and ''data-custom-attribute'' does not exist in type 'HTMLAttributes<HTMLDivElement>'.(2322)

What would be the perfect solution to fix this issue? Thanks a lot

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The data-custom-attribute and data-random-attribute properties do not exist in the React.HTMLAttributes type so you will not be able to use it. Additionally, data-custom-attribute and data-random-attribute are not used in any HTML element, hence your best bet would be to combine the existing React.HTMLAttributes type (to still get access to common HTMLDivElement element attributes) with your own CustomAttrs to be able to use specific ones for your use case:

interface CustomAttrs {
  'data-custom-attribute': string;
  'data-random-attribute': string;
}

type DivAttrs = {
  container?: React.HTMLAttributes<HTMLDivElement> & CustomAttrs,
}
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