How do I get the TypeScript engine to allow custom HTML attributes in JSX?

11,317

Solution 1

React type definition file (by default - index.d.ts when staring with create-react-app) contain list of all the standard HTML elements, as well as known attributes.

In order to allow custom HTML attributes, you need to define it's typing. Do that by expanding HTMLAttributes interface:

declare module 'react' {
  interface HTMLAttributes<T> extends AriaAttributes, DOMAttributes<T> {
    // extends React's HTMLAttributes
    custom?: string;
  }
}

Solution 2

Note: If an attribute name is not a valid JS identifier (like a data-* attribute), it is not considered to be an error if it is not found in the element attributes type.

<div data-custom="bar" />

https://www.typescriptlang.org/docs/handbook/jsx.html#attribute-type-checking https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/data-*

Share:
11,317
Sam
Author by

Sam

Senior JavaScript Engineer JavaScript, TypeScript, HTML, CSS, Node, Gulp, C#, Animation

Updated on June 29, 2022

Comments

  • Sam
    Sam almost 2 years

    I presume the TypeScript engine within Visual Studio Code has received an update that is now complaining for the first time that my pre-existing custom props on HTML elements are invalid. This is on a Babel/React/JSX project with no TypeScript whatsoever.

    <div custom="bar" />
    

    Note: they are (technically) invalid, but I consume them, so I know what I'm doing (it's intentional).

    See it on CodePen!

    See also

  • janith1024
    janith1024 almost 6 years
    add details to the answer
  • sɐunıɔןɐqɐp
    sɐunıɔןɐqɐp almost 6 years
    Welcome to Stack Overflow! Please don't just throw your source code here. Be nice and try to give a nice description to your answer, so that others will like it and upvote it. See: How do I write a good answer?
  • Artem Shmatkov
    Artem Shmatkov almost 3 years
    This breaks typescript type checking for the 'react' module.