Home > Mobile >  Extending React Types for CSS custom attributes
Extending React Types for CSS custom attributes

Time:11-09

I'm converting my React project to TypeScript, but can't figure out how to extend React.HTMLPorps to accept custom CSS data-attributes.

A common pattern that I use in my project is:

const MyComponent = ( ) => <div mycustomattr="true"/>;

I've tried creating an interface like so:

interface ExtendedDiv extends HTMLProps<HTMLDivElement> {
    mycutomattr: "true" | "false";
};

However, I'm not sure how to apply this to JSX div element.

CodePudding user response:

I can see 2 ways:

  1. easiest way is to rename atribut - custom => data-custom. But this will results in:
<div data-custom="true" />
  1. extend react interface HTMLAttributes but it will allow this attribute to all elements
interface HTMLAttributes<T> extends AriaAttributes, DOMAttributes<T> {
  // extends React's HTMLAttributes
  custom?: boolean;
}
  • Related