How do I get the TypeScript engine to allow custom HTML attributes in JSX?
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-*
Sam
Senior JavaScript Engineer JavaScript, TypeScript, HTML, CSS, Node, Gulp, C#, Animation
Updated on June 29, 2022Comments
-
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
- How do I add attributes to existing HTML elements in TypeScript/JSX? (posted by myself over a year ago and doesn't work any more).
- JSX | Type Checking
-
janith1024 almost 6 yearsadd details to the answer
-
sɐunıɔןɐqɐp almost 6 yearsWelcome 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 almost 3 yearsThis breaks typescript type checking for the 'react' module.