React Typescript allow to add custom data-* attributes. But is it possible to add custom attributes like 'name' || 'test' act. ?
<span name="I'm causing a type error" data-test="I'm Working"/>
Bold added by me.
type error: Type '{ children: Element; name: string; data-test: string; }' is not assignable to type 'DetailedHTMLProps, HTMLSpanElement>'. Property 'name' does not exist on type 'DetailedHTMLProps, HTMLSpanElement>'. TS232
"react": "^16.7.0",
"typescript": "^3.2.4",
- The Web Dev How to Add Custom HTML Attributes in React? Sometimes, we want to add custom HTML attributes in React. In this article, we’ll look at how to add custom HTML attributes in React. To add custom HTML attributes in React, we can just add them as we do with regular HTML element attributes.
How to create React components with TypeScript 1 Functional components with TypeScript. You can create functional components in TypeScript just like you would in JavaScript. ... 2 Class components in TypeScript. Although I default to writing functional components, some cases require me to work with class components as well. 3 Conclusion. ...
One recently was using custom HTML Attributes on DOM elements. This piece of code solved my issue, and allows you to add any custom HTML attributes when using TypeScript. Are you sure you want to hide this comment?
Class components in TypeScript 1 Type-safe state in class components. 2 Constructors. We'll typically use constructors to initialize our class component's state. If we don't do this and we run... 3 Default props. The React component is smart enough to inherit the prop types. In the example, title is a required... More ...
there is another way... skipping the static check (typescript don't do dynamic)
{
const allowedProps = {test: "not-data-attribute"}
<span {...allowedProps}/>
}
in react 16+ it is possible, see
probem is that typescript didnt know about it(yet)
but you can still add @ts ignore for typechecking
{ //@ts-ignore
<span name="I'm causing a type error" data-test="I'm Working"/>
}
Create any file with extension .d.ts
in your project
and just extend the button interface in the JSX namespace.
I'm using this for creating amp pages with React.
declare namespace JSX {
interface ExtendedButton
extends React.DetailedHTMLProps<
React.ButtonHTMLAttributes<HTMLButtonElement>,
HTMLButtonElement
> {
customAttribute?: string;
}
interface IntrinsicElements {
button: ExtendedButton;
}
}
simple add custom attribute start with data-
, in some case you may start with aria-
<div data-attr={3} data-nothing="super">hover</div>
it seems typescript knows custom attribute with those prefix, check this link
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With