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

103
Views
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 answers
Answer question

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 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!